Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

jQuery date validation

Status
Not open for further replies.

JBellTek

Programmer
Jun 11, 2009
29
US
I am writing a date validation function using jQuery, and seem to have run into a snag. Before I go into detail on the actual date, I run a quick regex to make sure that the format is right, but it is returning false on some dates that I know are valid. For instance, 01/22/2010 is fine, but it fails 11/22/2010. I know it has to be my regex string, but I don't know what I am doing wrong. Thoughts?

Code:
     jQuery.validator.addMethod("date", function(value, element) {
         var pass = this.optional(element) || /^(\d{2})(\/\d{2})(\/\d{4})$/.test(value);
         if (pass == false) {
           errorMsg = ('Must be in Date format mm/dd/yyyy');
           return 0;
         } else {
           etc.
 
I don't think your regerx is at fault, as both of these show "true" for me:

Code:
alert(/^(\d{2})(\/\d{2})(\/\d{4})$/.test('01/22/2010'));
alert(/^(\d{2})(\/\d{2})(\/\d{4})$/.test('11/22/2010'));

Therefore, I'd suggest debugging your function further (put a breakpoint in at the start to ensure "value" is what you think it really is).

Dan



Coedit Limited - Delivering standards compliant, accessible web solutions

Dan's Page [blue]@[/blue] Code Couch:
Code Couch Tech Snippets & Info:
 
Hi

Just because we are talking about debugging. Pointless parenthesis ( () ) makes the debugging of regular expressions harder. Beside that, unnecessary capturing of groups slows down the matching.
Code:
[gray]// no[/gray]
[fuchsia]/^(\d{2})(\/\d{2})(\/\d{4})$/[/fuchsia][teal].[/teal][COLOR=darkgoldenrod]test[/color][teal]([/teal]value[teal])[/teal]

[gray]// yes[/gray]
[fuchsia]/^\d{2}\/\d{2}\/\d{4}$/[/fuchsia][teal].[/teal][COLOR=darkgoldenrod]test[/color][teal]([/teal]value[teal])[/teal]

Feherke.
 
BillyRayPreachersSon:

You are correct. I have fixed this problem, and it was not the regex at fault. Using breakpoints did help me find the error farther down in the code.

feherke:
Thank you for your input. I have been attempting to better my skills with regex, and your comment helps me to refine my abilities.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top