Recommand · October 14, 2021 0

Method to validate if string has only hyphens, spaces, Uppercase and digits

Recently I’ve been trying to create a method to make sure a string has certain types of chars. Yet when I tried using the method, it stops checking if the chars are that way on the 4th character.

For example I tried using 4 lowercase letters and it tells me it’s false, but when I try to use invalid characters (lowercase, symbols) on the 5th character, it says it’s true:

public bool CarLicensePlateCheck(string m)
{
        if (m.Length >= 4 && m.Length <= 12)
        {
            foreach(char c in m)
            {
                if (char.IsDigit(c) == true ||  char.IsUpper(c)==true || char.IsWhiteSpace(c)==true || c.Equals("-"))
                    return true;
                else
                    break;
            }
            return false;
        }
        else
            return false;
}

You need to check if the character is not valid and return false immediately and then return true outside of the foreach (because at that point you’ve validated all the characters). What you have stops validating after the first character because if the first character is valid it just returns true and if it isn’t it breaks from the foreach and returns false.

public bool CarLicensePlateCheck(string m)
{
    if (m.Length >= 4 && m.Length <= 12)
    {
        foreach(char c in m)
        {
            // If it's not a valid character return false
            if (!char.IsDigit(c) 
                && !char.IsUpper(c)
                && !char.IsWhiteSpace(c)
                && c != '-')
                return false;
        }

        // all characters have been validated so return true
        return true;
    }
    else
        return false;
}

You can try regular expressions:

  public bool CarLicensePlateCheck(string m) =>
    m != null && Regex.IsMatch(m, @"^[A-Z0-9\s\-]{4,12}$");