1

I want use a RegularExpressionValidator for a date in this form yyyy-mm-dd (example: 2012-11-29) and here is my expresion:

/^(19[789]\d|20[0123]\d)-(0\d|1[012]|\d)-(31|30|[012]\d|\d)$/

I test it on http://www.quanetic.com/Regex and it works but if I do this in my asp.net application it doesn't work

 <tr>
   <td>Gültig ab:</td>
   <td><asp:TextBox ID="txtVon" runat="server" ></asp:TextBox></td>  
   <td><asp:ImageButton ID="imgVon" runat="server" ImageUrl="images/Calender.ico" Width="15" Height="15" />
     <asp:CalendarExtender runat="server" ID="E_Von" TargetControlID="txtVon" Format="yyyy-MM-dd" PopupButtonID="imgVon"/></td>        
   <td>
     <asp:RequiredFieldValidator ID="ValVon" 
       runat="server" ForeColor="red" 
       ErrorMessage="*" ControlToValidate="txtVon"></asp:RequiredFieldValidator>
     <asp:RegularExpressionValidator ID="regVon"   
       runat="server" ControlToValidate="txtVon" 
       ErrorMessage="*Format" ForeColor="red" 
       ValidationExpression="/^(19[789]\d|20[0123]\d)\-(0\d|1[012]|\d)\-(31|30|[012]\d|\d)$/"></asp:RegularExpressionValidator>
   </td>
 </tr>

Where is the error?

Dave New
  • 38,496
  • 59
  • 215
  • 394
Tarasov
  • 3,625
  • 19
  • 68
  • 128
  • How is it not working? Is it not being triggered at all, or is it triggering at the wrong times? – David Brunow Nov 29 '12 at 13:12
  • Even though the expression is fixed with og Grand's answer http://stackoverflow.com/a/13626639/736079, the real solution to your problem can be found by using the `CompareValidator` to validate the Datatype for the contents. See http://stackoverflow.com/a/939852/736079 – jessehouwing Nov 29 '12 at 13:32

2 Answers2

5

Just remove char "/" in the begining and in the and of the string.

And you will have

ValidationExpression="^(19[789]\d|20[0123]\d)-(0\d|1[012]|\d)-(31|30|[012]\d|\d)$"
og Grand
  • 114
  • 3
  • The / regex / syntax is the Javascript syntax for a Regexp object, but this expression is shared between clientside (javascript) and serverside (C# or VB.NET) and thus should not use any language specific constructs. – jessehouwing Nov 29 '12 at 13:28
  • Thing, that you have written - unreal. – og Grand Nov 29 '12 at 13:36
  • I was trying to clarify why your answer is the correct answer. I can't figure out whether your comment is meant as a compliment, or as a statement to flag something wrong in my comment... – jessehouwing Nov 29 '12 at 14:09
1

I use the following, which works ok.

\A(?:^(19|20)\d\d([- /.])(0[1-9]|1[012])\2(0[1-9]|[12][0-9]|3[01])$)\Z
UnitStack
  • 1,175
  • 1
  • 11
  • 28
  • This has the opposite problem: `\A` and `\Z` are not supported in JavaScript, so this will fail if the validation is done on the client. But they're redundant anyway, since the regex is already anchored with `^` and `$`. – Alan Moore Nov 29 '12 at 14:14