dLcreations
dLcreations

Reputation: 377

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

Upvotes: 1

Views: 346

Answers (2)

Onur CAN
Onur CAN

Reputation: 81

You can use like that.

public partial class xxx
{
[RegularExpression(@"^\+?\(?([0-9]{2})\)?([ .-]?)([0-9]{4})\2([0-9]{4})", ErrorMessage = "")]
public string MobileNumber { get; set; }
}

Upvotes: 1

TWiStErRob
TWiStErRob

Reputation: 46470

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})

Upvotes: 0

Related Questions