1

I've 2 regular expression:

  1. string regex1 = "(?i)(^(?!^.*?admin)(?!^.*?admin[admin\d]).*$)"; this will check for 'admin' substring in the given string and case is insensitive.

  2. string regex2 = "^[^<>?]{5,100}$"; this will check for special char(^<>?) and length between 5 to 100 only.

I want a regular expression where both the regex can be validated at once with the use of only single regex.

Ex-

<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"
    ControlToValidate="txtBox1" ErrorMessage="Validation Failed!"
    ValidationExpression="(?i)(^(?!^.*?admin)(?!^.*?admin[admin\d]).*$)">
</asp:RegularExpressionValidator>

<asp:RegularExpressionValidator ID="RegularExpressionValidator2" runat="server"
    ControlToValidate="txtBox2" ErrorMessage="Length Validation Failed!"
    ValidationExpression="^[^<>?]{5,100}$">
</asp:RegularExpressionValidator>

Q. Can we have a single "RegularExpressionValidator" that serves both the above functionality?

VLAZ
  • 26,331
  • 9
  • 49
  • 67
Bit2Dev
  • 57
  • 6

1 Answers1

1

The (?i)(^(?!^.*?admin)(?!^.*?admin[admin\d]).*$) regex is too redundant, it is equal to (?i)^(?!^.*?admin).*$. It basically matches any string that contains no admin substring.

The ^[^<>?]{5,100}$ regex disallows <, > and ? in the string and sets string length limit.

Combining the two is done by replacing the .* in the first pattern with the consuming part of the second regex ([^<>?]{5,100}):

(?i)^(?!^.*?admin)[^<>?]{5,100}$

Details

  • (?i) - case insensitive mode on
  • ^ - start of string
  • (?!^.*?admin) - no admin substring allowed anywhere after 0 or more chars other than line break chars, as few as possible
  • [^<>?]{5,100} - five to a hundred chars other than <, > and ?
  • $ - end of string.
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • 1
    Thanks a lot Wiktor Stribiżew, I simply copied your answer and it's working as expected :) – Bit2Dev Feb 05 '20 at 07:59
  • @Bit2Dev Also, see [the regex demo online](https://regex101.com/r/mvGkc2/1). – Wiktor Stribiżew Feb 05 '20 at 08:02
  • Hey @Wiktor Stribiżew, I found 1 issue, the above mentioned regex (?i)^(?!^.*?admin)[^<>?]{5,100}$ is working fine in my POC but if put in the required project, its throws error in WebResource.axd file. – Bit2Dev Feb 08 '20 at 09:24
  • @Bit2Dev The pattern in the answer will work on the server side, it won't work on the client side as JS RegExp does not support inline modifiers. You must remove `(?i)` and use `^(?!^.*?[Aa][Dd][Mm][Ii][Nn])[^<>?]{5,100}$` – Wiktor Stribiżew Feb 08 '20 at 11:54