Regex RegularExpressionValidator

104 views Asked by At

Sorry if this has already been answered but I could not find it here. I know its possible but have very limited knowledge of Regex. I have an ASP.NET project and I would like to check to see if the first two characters of a value starts with GY, BT, JE, and if so trigger a validation failure.

What I have at the moment inside my RegularExpressionValidator is:

/^(?i)[GY]{2}|^(?i)[BT]{2}|^(?i)[JE]{2}/

Any help would be greatly appreciated.

Thanks Jon

4

There are 4 answers

0
Kuba Wyrostek On BEST ANSWER

I am not sure if I understand correctly, but I guess your expression would be:

/^(GY|BT|JE)/

This would match all values starting with GY or BT or JE.

If on the other way you would like to allow all strings that do not start with BY or BT or JE, this would be

/^(?<!(GY|BT|JE)).*/
1
Teejay On

This should do the trick

string strRegex = @"/^(?i)[GY]{2}|^(?i)[BT]{2}|^(?i)[JE]{2}/";

Regex re = new Regex(strRegex);
if (re.IsMatch(inputString))
    return (true);
else
    return (false);
0
Mitya On

Remember that [] is a range, and makes no stipulation on the order that the characters should appear. So:

[GY]{2} would match not only the desired 'GY' but also 'GG' or 'YY'. Try this:

/^(GY|BT|JE)/
0
Ωmega On

Simple task - use regex ^(GY|BT|JE) or ^(?:GY|BT|JE)

<script  runat="server">
  sub submit(sender As Object, e As EventArgs) 
    if Page.IsValid then 
      lbl.Text="OK"
    else 
      lbl.Text="NOT OK"
    end if
  end sub
</script>

<!DOCTYPE html>
<html>
  <body>
    <form runat="server">Enter text here:
      <asp:TextBox id="txtbox1" runat="server" />
      <br /><br />
      <asp:Button text="Submit" OnClick="submit" runat="server" />
      <br /><br />
      <asp:Label id="lbl" runat="server" />
      <br />
      <asp:RegularExpressionValidator 
        ControlToValidate="txtbox1"
        ValidationExpression="^(GY|BT|JE)"
        EnableClientScript="false"
        ErrorMessage="Error"
        runat="server" />
    </form>
  </body>
</html>