views:

147

answers:

2

Given the following RegEx expression, testing this on regexlib.com with the string "2rocks" produces a 'match'. However, in my .NET application, it's causing the regex validator to throw a validation error.

^(?=.*[A-Za-z])[a-zA-Z0-9@\-_\+\.]{6,32}$

If I change the string to "rocks2" in both my application and regexlib.com, I get a match in both places.

The goal is to have a regex expression, that requires the string to be between 6-32 chars in length, and allow A-Z, a-z, numeric and the other special characters included in the regex, forcing at least ONE letter.

Here's the ASP mark up, I'm totally confused.

<asp:regularexpressionvalidator 
    id=vldRegEx_LoginID 
    runat="server" 
    ErrorMessage="Regex Error Message" 
    Display="Dynamic" 
    ControlToValidate="txtLoginID" 
    ValidationExpression="^(?=.*[A-Za-z])[a-zA-Z0-9@\-_\+\.]{6,32}$">
        <img src="images/error.gif" border="0">
 </asp:regularexpressionvalidator>
+6  A: 

The ValidationExpression you pass is actually the expression that is used as a client side javascript regex. Javascript regex doesn't support all the features of .NET regex, which is why you're running into issues. You have two options:

  • Turn off client side validation and use server side validation only (set EnableClientScript=false on the validator)
  • Rewrite the regex to be a valid javascript regex (javascript regex tester: http://regexpal.com/)
Chris Hynes
A: 

You may be being bitten by this bug. Lookahead assertions should be avoided in JavaScript RegExp.

bobince