Search code examples
c#regexasp.net-mvcenterprise-library

Model state invalid when using custom RegexAttribute


Regex not working in code but works in tool: \+?\(?([0-9]{2})\)?([ .-]?)([0-9]{4})\2([0-9]{4})

This regex is used in Custom Attribute in MVC application. Where it always invalidate the model. While it works accurately in online tools.

I am trying to validate phone number is this format: +(55) 7564 6242


Solution

  • You didn't specify the language, but from Attribute and MVC I'm guessing C#.

    You have to escape your regex strings for the source code.

    Original pattern

    \+?\(?([0-9]{2})\)?([ .-]?)([0-9]{4})\2([0-9]{4})
    

    Regular C# (or Java) String

    string pattern = "\\+?\\(?([0-9]{2})\\)?([ .-]?)([0-9]{4})\\2([0-9]{4})"
    

    C# verbatim (better for regex / hardcoded Windows paths)

    string pattern = @"\+?\(?([0-9]{2})\)?([ .-]?)([0-9]{4})\2([0-9]{4})"
    

    See C# String Literals for more info.

    Without Escape
    An unescaped string would result in a pattern that the regex engine just doesn't recognize (see output below), because \\ is special in your source language strings. It probably escapes it something like this

     string pattern = "\+?\(?([0-9]{2})\)?([ .-]?)([0-9]{4})\2([0-9]{4})";
     print(pattern);
    

    would output (note the missing \\s)

    +?(?([0-9]{2}))?([ .-]?)([0-9]{4})2([0-9]{4})