Search code examples
regexasp.net-mvcvalidation

Custom Regex validation firing on all inputs


I'm writing a .NET MVC application and using unobtrusive validation to sanitize my client inputs based on data annotations in my model. I have an input that I do not want to allow HTML tags into and would like to display a custom error message if an html tag is entered. As such I have created a data annotation with a custom regex expression to cover these conditions, like so:

[Required(ErrorMessage = "You must provide a First Name.")]
[RegularExpression(@"<[a-z][\s\S]*>", ErrorMessage = "Invalid character")]
[DisplayName("First Name")]
public string FirstName { get; set; }

The issue with this is, no matter what character, whether it be <test> or whether it be abc will cause the Invalid Character message to appear. The required attribute works fine, and if I try a simple regex such as:

[RegularExpression("[a-z]", ErrorMessage = "Invalid character")] 

This works 100% as expected, leading me to believe my regex is incorrect, nut I know it works for HTML validation as I can prove it out with online tools. What am I doing wrong?


Solution

  • If you take a look at the documentation of the RegularExpressionAttribute, it states:

    Specifies that a data field value in ASP.NET Dynamic Data must match the specified regular expression.

    So your attribute is doing the exact opposite of what you want. Try with:

    [RegularExpression(@"^(?!.*<.*>).*$", ErrorMessage = "Invalid character")]