Check if entered value is numeric and if it has 9 characters

3

How can I check if a value is numeric, and only numeric (no occurrence of periods, dashes, etc.), regardless of how many characters the number contains, in addition to having exactly 9 characters, neither more nor less?

  

Examples accepted: 111111111, 222222222, 123456789

     

Examples not supported: 1,000, 3.50, 12345678

SOEN Document

    
asked by anonymous 20.03.2014 / 16:55

1 answer

6

You can get this information using the ^\d{9}$ mask in a regular expression, which, in addition to checking the number of characters ( {9} ), checks to see if they are numeric ( \d ):

string valor = "123456789";
bool ehValido = Regex.IsMatch(valor, @"^\d{9}$");

It is also possible via LINQ :

string valor = "123456789";
bool ehValido = valor.Length == 9 && valor.All(char.IsDigit);

For efficient building regular expressions, I recommend RegexPal .

    
20.03.2014 / 16:55