Check if the given value is numerical and has 9 characters

Asked

Viewed 9,340 times

3

How can I verify if a value is numerical, and only numerical (without occurrence of points, strokes, etc.), regardless of the amount of characters that the number contains, besides having exactly 9 characters, neither more nor less?

Accepted examples: 111111111, 222222222222, 123456789

Examples not accepted: 1,000, 3.50, 12345678

Original of the SOEN

1 answer

6


It is possible to get this information using the mask ^\d{9}$ in a regular expression, which in addition to checking the amount of characters ({9}), checks if they are numerical (\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 construction of regular expressions, recommend the site Regexpal.

  • 1

    Another interesting Regex checker is: http://www.regexplained.co.uk/

  • @gmsantos liked the fact that he explained the regex, but I think it would fit a data field :-)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.