Home > Back-end >  Custom regex validation ASP.NET Webforms
Custom regex validation ASP.NET Webforms

Time:02-04

I have a custom validator that is supposed to prompt the user to removed certain characters if found in the textbox. However, the validation is coming up even when there are no matching characters in the textbox. I have tested the regex before implementing it in asp.net but it cannot pass the validation.

asp:RegularExpressionValidator ID="revHarmfulCharacters" runat="server" 
   ErrorMessage="Please remove these characters where present  >, <, /*, *\, --, |, {}" 
   ControlToValidate="txt_comment" ValidationExpression="[/^{}|<>(--)(/*)(*\/)(>=)]" 
   Display="Dynamic">
</asp:RegularExpressionValidator>

The regular expression should be shown for this case

Image with character

But should not be shown for this case

Image without character

This is a test of the regex that I did

Regex test

CodePudding user response:

Regular expression validation are written to match valid input. Since your regex pattern was not matched entire input string in both cases, so the error message is showed up in both cases.

You could try this pattern: ^[^/{}|<>(--)(/*)(*\/)(>=)^] $

CodePudding user response:

Edit the regex and test it. Regex is ValidationExpression="[\^{}|<>(--)(*)(*\/)(>=)]" Try this

I try with this <[email protected]>. It is matched.

enter image description here

I try with this [email protected]. It is not matched.

enter image description here

  • Related