Search code examples
.netregexasp.net-mvcmodel-validation

Conditional regex in model validation


I am new to regex and am validating a phone number. If the phone number starts with 011. The number can be greater than 10 digits. If it doesn't start with 011 it must be between 10-15 digits. Currently I have (?(011)\d{10, 15}|\d{7,}) but that is not working. I know I am missing something just can't figure out what it is.


Solution

  • How about

    "(011\d{7,}|\d{10,15})"
    

    Assumes you don't want to allow any non-digits, and that numbers beginning with 011 must be at least 10 digits long.

    If not using a ValidationExpression you may have to anchor the pattern with ^ and $.