Search code examples
cvalidationdigitsletter

Numbers and letters validation in C


I am new at programming and I faced up with validation. I try to write a program where the program gets the user’s Name and Age as inputs. And I need to check if the name contains only letters (it can have spaces) and if age is only from numbers. I tried to use the functions IsAlpha() and IsDigit() but I think it’s not the right way in my program because it only checks the first character. For example, if the user inputs “Jane123 or J0nas” an error appears and the same with numbers.

I think I should use something with while of if. Any suggestions? Thanks.


Solution

  • Either you iterate over your input and check every single character or alternatively use strspn.

    const char alpha[] = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    const char digit[] = "0123456789";
    
    if (strlen(Name) != strspn(Name, alpha)) {
        printf("Invalid Username\n");
        exit(-1);
    }
    
    if (strlen(Age) != strspn(Age, digit)) {
        printf("Invalid Age\n");
        exit(-1);
    }
    

    But be aware, if you got your inputs from functions, like fgets, you probably have a containing newline character and it is required that you trim them first (remove all whitespace from the beginning and/or the end).