Home > Blockchain >  Validating ID Number C#
Validating ID Number C#

Time:12-06

I am working on this method that validates a student Id number. The credentials of the ID number are; the first character has to be 9, the second character has to be a 0, there can not be any letters, and the number must be 9 characters long. The method will return true if the student id is valid. When I go to test the method manually through main it comes out as true, even when I put in a wrong input. In my code, I have the if statements nested, but I originally did not have them nested. What is a better way to validate the input to align with the credentials of the ID number? Would converting the string into an array be more ideal?

 public static bool ValidateStudentId(string stdntId)
        {
            string compare = "123456789";
            if (stdntId.StartsWith("8"))
            {
                if (stdntId.StartsWith("91"))
                {
                    if (Regex.IsMatch(stdntId, @"^[a-zA-Z] $"))
                    {
                        if (stdntId.Length > compare.Length)
                        {
                            if (stdntId.Length < compare.Length)
                            {
                                return false;
                            }
                        }
                    }
                }
            }

screenshot of my main. The method was made in a class called student.

CodePudding user response:

You can try regular expressions:

public static bool ValidateStudentId(string stdntId) => stdntId != null &&
  Regex.IsMatch(stdntId, "^90[0-9]{7}$");

Pattern explained:

  ^        - anchor - string start 
  90       - digits 9 and 0
  [0-9]{7} - exactly 7 digits (each in [0..9] range) 
  $        - anchor - string end

So we have 9 digits in total (90 prefix - 2 digits 7 arbitrary digits), starting from 90

CodePudding user response:

Would converting the string into an array be more ideal?

Every string is kind of a char[] and you can access every char at it's index like if it was an array. So no, there is no need to convert it to an array(if you wanted a copy of all chars as array anyway you could use ToCharArray).

What is a better way to validate the input to align with the credentials of the ID number?

Well, you could use regex, but for this simple task pure string methods are fine:

public static bool ValidateStudentId(string stdntId)
{
    return stdntId?.Length == 9
        && stdntId.StartsWith("90")
        && stdntId.All(char.IsDigit);
}

Why your code doesn't work? You don't check your own rules which are:

the first character has to be 9, the second character has to be a 0, there can not be any letters, and the number must be 9 characters long

  • Related