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)?
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.
You can use
[RegularExpression(@"^(?:[a-zA-Z0-9 ]|<(?= ))+$", ErrorMessage = "some message")]
^– start of string
(?:– start of a non-capturing group:
[a-zA-Z0-9 ]– a letter or digit or space
<(?= )– a
<that is followed with a space
)+– end of group, match one or more times
$– end of string.
See the regex demo.