In C#, how can I see if the first character in an account is a specific value?

Viewed 276

I have a string that contains a 15 digit account number. The first digit cannot be a 0,1, 8 or 9. I want to say something like:

public bool ValidateAccountNumber(string Accountnumber )
{
    char[] Invalidboro = new char[] { '0', '1', '8', '9'};
    bool returnValue = true;

    if (Accountnumber.Length != 15 || Accountnumber.Substring(1, 1).Contains(Invalidboro))
    {
        returnValue = false;
    }
    return returnValue;
}

I'm new to C# and not sure how to do this.

4 Answers

regex

public bool ValidateAccountNumber(string Accountnumber)
{
    return Accountnumber != null && Regex.IsMatch(Accountnumber, "^[2-7][0-9]{14}$");
}

You just have to combine all required checks with &&

using System.Linq;

...

// static: we don't want this in the method
public static bool ValidateAccountNumber(string Accountnumber) {
  return // Not null 
         Accountnumber != null &&
         // Contains exactly 15 characters 
         Accountnumber.Length == 15 &&
         // All characters are digits
         Accountnumber.All(c => c >= '0' && c <= '9') &&
         // Doesn't start from 0, 1, 8, 9 
       !(new char [] {'0', '1', '8', '9'}.Any(c => c == Accountnumber[0]));
}

I recomend you to do it in this way:

public bool ValidateAccountNumber(string accountNumber)
{
    var invalidBoro = new [] { '0', '1', '8', '9'};

    if (accountNumber != null && accountNumber.Length == 15)
    {
        return !invalidBoro.Contains(accountNumber[0]);
    }

    return false;
}

It checks three four conditions about AccountNumber:

  • It should not be null
  • It should have exactly 15 characters
  • It should not begin with 0, 1, 8 or 9
  • All characters should be digits

public static bool ValidateAccountNumber(string Accountnumber )
{
    var Invalidboro = new[] { '0', '1', '8', '9'};

    return Accountnumber != null &&
           Accountnumber.Length == 15 &&
           !Invalidboro.Contains(Accountnumber[0]) &&
           Accountnumber.All(c => c >= '0' && c <= '9');
}

Just to clarify on the !Invalidboro.Contains(Accountnumber[0]) part:

  • Invalidboro is your array of invalid starting chars.
  • We are checking if it contains the first char of Accountnumber (the [0] is the first element of an array and a string is an array of char).
  • If it contains it, then it's invalid. But the method should return true on the valid numbers, so we negate it, with the !. In other words, this means: it's valid if it does not start with some invalid char.
Related