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

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

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x