Home > other >  Regex for US cell phone number with all zeros not being allowed
Regex for US cell phone number with all zeros not being allowed

Time:06-30

I have a cellphone field that is being validated as such-

[Required(ErrorMessage = "Cell phone is required"),
            RegularExpression(Constants.PhoneRegex, ErrorMessage = "Invalid phone number")]
public string CellPhone { get; set; }

This is currently being validated for US phone numbers with this regex, PhoneRegex = @"^(?!0 $)(\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4}))$"; which I found from https://www.oreilly.com/library/view/regular-expressions-cookbook/9781449327453/ch04s02.html

Now there is a new requirement to not allow user to enter all zeros. So I tried ^(?!0 $)(\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4}))$ which I found from another thread RegEx for phone number, all zeros not allowed

This one works when I test it on https://rubular.com/ but in my code it does not work

Example:-
Cellphone   |  Actual   |  Expected
------------------------------------
4561237890  |  //true   |  true
1234        |  //false  |  false
0000000000  |  //true   |  false

CodePudding user response:

Try this

var regEx = @"^(?<Number>[0-9]{3}[-.\s][0-9]{3}[-.\s][0-9]{4})(?<AllZero>[0]{0,9})$";
var match = Regex.Match(MYSTRING_TO_TEST, regEx, RegexOptions.IgnoreCase);
string validateNumber = match.Groups["Number"].Value;
string allZeroNumber = match.Groups["AllZero"].Value;

If allZeroNumber match is all 0 digit.

CodePudding user response:

You can use

^(?!(?:\D*0) \D*$)\(?([0-9]{3})\)?[-. ]?[0-9]{3}[-. ]?[0-9]{4}$

Here,

  • ^ - start of string
  • (?!(?:\D*0) \D*$) - no only one or more 0 digits in the string
  • \(? - an optional ( char
  • [0-9]{3} - three digits
  • \)? - an optional ) char
  • [-. ]? - an optional space, - or . char
  • [0-9]{3} - three digits
  • [-. ]? - an optional space, - or . char
  • [0-9]{4} - four digits
  • $ - end of string.
  • Related