regular expressions (dates and money)


Friday, August 11, 2006

Using regular expressions to validate user input is very handy, but they can be very difficult to construct since their syntax is foreign to most .NET programmers.  I am often finding myself in need of adding a custom validation control to a web form that requires a valid date format inputted by the user.  I built the following regular expression to handle short dates and it seems to work well:

^(((([13578])|(0[13578])|(1[02]))\/(([1-9])|([0-2][0-9])|(3[01])))|((([469])|(0[469])|(11))\/
(([0-9])|([0-2][0-9])|(30)))|((([2])|([02]))\/(([1-9])|([0-2][0-9]))))\/((\d{2})|(\d{4}))$


You can better see the logic by expanding the expression in notepad, using tabs and carriage returns.

Another common use for regular expressions is to validate currency data entered by a user.  I found the following currency expression somewhere on the net and it has worked well for me:
^-?\d+(\.\d{2})?$

9:20:55 PM   | c# |


Comments



Post a comment on:

regular expressions (dates and money)

(HTML will not work within the comments)


Author  
Author Email  
Comment Title  
Comment  
 characters left
Captcha
Enter code in image: