3

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?

Halter
  • 48
  • 2
  • 6
  • 30
  • Use `@"<[a-z][\s\S]*>"` – Wiktor Stribiżew Apr 24 '18 at 22:51
  • @WiktorStribiżew I have tried that approach but just did again, it leaves the same result. Validation fires on all values. Also, I'm not too sure how my question is a duplicate of the linked one? Maybe I'm dumb but I don't see how it answers my question. – Halter Apr 25 '18 at 11:17
  • Ok, so that means you want to only show the error if a string *contains* `<{LETTER}{anything_here}>`, right? Probably you want `@"^.*<[a-zA-Z][^>]*>.*$"` – Wiktor Stribiżew Apr 25 '18 at 11:20
  • @WiktorStribiżew Yeah my goal is string like `` or `a ` fail out, but input without html entities all work fine. Sadly that regex did not work either, when I input `a` into the textbox, the validation warning is triggered. – Halter Apr 25 '18 at 11:23
  • @WiktorStribiżew done – Halter Apr 25 '18 at 12:01
  • Try `^[^<>]*$` for a quicker regex. –  Apr 27 '18 at 20:22

1 Answers1

3

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")]
Thomas Ayoub
  • 29,063
  • 15
  • 95
  • 142
  • By god you're right! That did it! Not sure how I overlook that but thank you none the less! – Halter Apr 27 '18 at 13:39
  • Sometime it's hard to see the elephant in front of us, @Halter . Maybe you should take a look at the rubber duck debugging method ;) – Thomas Ayoub Apr 27 '18 at 15:26
  • 1
    You would think that if it _matches_ the regex, the error would be thrown, but I guess not. –  Apr 27 '18 at 20:38