Ben
Ben

Reputation: 1

Check if a string has a certain length and contains certain letters

So I want to check that a string has all these attributes:

This is my code:

Console.Write("IDnumber : ");
IDnumber= Console.ReadLine();
IDnumberLength = IDnumber.Length;
if (MemberNumber.Length == 5  && 
    char.IsLetter(IDnumber[0]) &&  <-- I know how to validate any letter but not certain letter
    char.IsDigit(IDnumber[1]) && 
    char.IsDigit(IDnumber[2]) &&
    char.IsDigit(IDnumber[3]) &&
    char.IsDigit(IDnumber[4]))

Upvotes: 0

Views: 1180

Answers (2)

Enigmativity
Enigmativity

Reputation: 117029

You could use Regex like this:

var regex = new Regex("^[OSJC][0-9]{4}$");

Console.WriteLine(regex.IsMatch("J1234"));
Console.WriteLine(regex.IsMatch("J124"));
Console.WriteLine(regex.IsMatch("X1234"));

That would give you:

True
False
False

In your code you could use it like this:

Console.Write("IDnumber : ");
IDnumber = Console.ReadLine();
if (Regex.IsMatch(IDnumber, "^[OSJC][0-9]{4}$"))
{
    // Success
}
else
{
    // Failed
}

Upvotes: 4

Dai
Dai

Reputation: 155035

Without using a regular-expressions:

Boolean isValid =
    value.Length == 5 &&
    ( value[0] == 'O' || value[0] == 'S' || value[0] == 'J' || value[0] == 'C' ) &&
    Char.IsDigit( value[1] ) &&
    Char.IsDigit( value[2] ) &&
    Char.IsDigit( value[3] ) &&
    Char.IsDigit( value[4] );

Upvotes: 0

Related Questions