ASP.NET MVC - Regex to allow less than character safely

Viewed 126

I have a ASP.NET MVC 5 app where my business users require to enter a < (less than sign). For their specific business segment the < is a common used sign. I know about the problem of XSS-Attacks, but I'm trying to find a solution to allow just the < without opening XSS-Attacks. I DON'T want to allow HTML, so I don't what to set [AllowHtml] or disable the validation rules. They should be turned on.

I thought about to only allow the < followed by a space, which isn't a valid html tag and isn't detected by ASP.NET as dangerous request. I assume that the best option would be to setup a regex, but I don't know how the regex should look like.

For example I want to extend this regex (Data annotation): [RegularExpression(@"^[a-zA-Z0-9 ]+$", ErrorMessage = "some message")] to allow < followed by a space.

Is there also anything to consider if I would allow < (followed by space)?

1 Answers

You can use

[RegularExpression(@"^(?:[a-zA-Z0-9 ]|<(?= ))+$", ErrorMessage = "some message")]

Details:

  • ^ - start of string
  • (?: - start of a non-capturing group:
    • [a-zA-Z0-9 ] - a letter or digit or space
    • | - or
    • <(?= ) - a < that is followed with a space
  • )+ - end of group, match one or more times
  • $ - end of string.

See the regex demo.

Related