-
need help in validation
Code:
void check_nric(char *string_check, int length_check)
{
int wrong, length, i;
int ctr = 0;
char field[15] = "NRIC Number";
do{
if(ctr != 0)
{
printf("\n\tPlease Enter [NRIC Number] Again: ");
}
new_get_nric(string_check,length_check,field);
wrong = 0; /* reset flag at top of loop */
length = strlen(string_check);
/*used to check if all digits are entered*/
for (i = 0; i < length; i++) /* <-------------- Using the length */
{
if ( !isdigit(string_check[i]) && strchr(string_check,'-') == NULL)
{
wrong = 1;
printf("\n\tUse only NUMBERS");
break;
}
}
ctr++;
/* note: the checking for space here is not necessary
* as the a [space] is not a valid numera thus an error will occur
*/
}while(wrong);
}
As you see i am this code will check the nric number that the user enters and it must be only digits.
How if i want to make the code as the nric number input must be 14 digits only and not less or more, and include the '-' symbol.'
Ex: 840402-10-5895
-
First thing this code needs is a consistent approach to indentation.
-
>How if i want to make the code as the nric number input must be 14 digits only and not less or more, and include the '-' symbol.'
This would be a good start:
Code:
#include <string.h>
int valid_nric ( const char *nric )
{
size_t len = strlen ( nric );
size_t match = strspn ( nric, "0123456789-" );
if ( len != 14 || match != 14 )
return 0;
return 1;
}
However, if the nric must have a specific number of digits separated by '-', for example, six digits followed by one dash followed by two digits followed by one dash followed by four digits, the above code is too relaxed. You would need to do a little bit more, though not much. Using the above function, a more restrictive solution is clear:
Code:
int valid_nric ( const char *nric )
{
size_t len = strlen ( nric );
size_t match = strspn ( nric, "0123456789-" );
if ( len != 14 || match != 14 )
return 0;
/*
* If it isn't a digit, it must be a dash */
*/
match = strspn ( nric, "0123456789" );
if ( match != 6 )
return 0;
nric += match + 1;
match = strspn ( nric, "0123456789" );
if ( match != 2 )
return 0;
nric += match + 1;
match = strspn ( nric, "0123456789" );
if ( match != 4 )
return 0;
return 1;
}
And it is a good idea to avoid using tabs in your code. If you must use tabs, convert them to spaces if your editor supports that feature. Tabs are evil.