9

I am trying to validate textbox with valid datetime format. I need to check 24 hours datetime format. So i input following text to my textbox 22.05.2013 11:23:22

But it still doesnt validate it correctly. I am totally new to regex. This is so far i have tried

$('#test1').blur(function(){
 var validTime = $(this).val().match(/^[0,1]?\d\/(([0-2]?\d)|([3][01]))\/((199\d)|([2-9]\d{3}))\s[0-2]?[0-9]:[0-5][0-9]?$/);
    debugger;
    if (!validTime) {
        $(this).val('').focus().css('background', '#fdd');
    } else {
        $(this).css('background', 'transparent');
    }
});

This is my fiddle

6
  • Where did you get the pattern form? Why is there [0,1]? that won't allow 22.05.2013. Commented Jan 7, 2014 at 13:22
  • @putvande From here stackoverflow.com/questions/16626942/… Commented Jan 7, 2014 at 13:24
  • Your regex uses slashes not dots for the date Commented Jan 7, 2014 at 13:24
  • What does this do debugger;? Commented Jan 7, 2014 at 13:26
  • @Jonathan debugger is just to debug the code Commented Jan 7, 2014 at 13:28

3 Answers 3

17

It's very hard to validate a date with a regular expression. How do you validate 29th of February for instance? (it's hard!)

Instead I would you use the built-in Date object. It will always produce a valid date. If you do:

var date = new Date(2010, 1, 30); // 30 feb (doesn't exist!)
// Mar 02 2010

So you'll know it's invalid. You see it overflows to March, this works for all the parameters. If your seconds is >59 it will overflow to minutes etc.

Full solution:

var value = "22.05.2013 11:23:22";
// capture all the parts
var matches = value.match(/^(\d{2})\.(\d{2})\.(\d{4}) (\d{2}):(\d{2}):(\d{2})$/);
//alt:
// value.match(/^(\d{2}).(\d{2}).(\d{4}).(\d{2}).(\d{2}).(\d{2})$/);
// also matches 22/05/2013 11:23:22 and 22a0592013,11@23a22
if (matches === null) {
    // invalid
} else{
    // now lets check the date sanity
    var year = parseInt(matches[3], 10);
    var month = parseInt(matches[2], 10) - 1; // months are 0-11
    var day = parseInt(matches[1], 10);
    var hour = parseInt(matches[4], 10);
    var minute = parseInt(matches[5], 10);
    var second = parseInt(matches[6], 10);
    var date = new Date(year, month, day, hour, minute, second);
    if (date.getFullYear() !== year
      || date.getMonth() != month
      || date.getDate() !== day
      || date.getHours() !== hour
      || date.getMinutes() !== minute
      || date.getSeconds() !== second
    ) {
       // invalid
    } else {
       // valid
    }

}

JSFiddle: http://jsfiddle.net/Evaqk/117/

Sign up to request clarification or add additional context in comments.

3 Comments

Can we also check on this date time format 22/05/2013 11:23:22? previously i used 22.05.2013 11:23:22. so if user enter / or . then both are valid
Sure. Change the regexp to /^(\d{2}).(\d{2}).(\d{4}).(\d{2}).(\d{2}).(\d{2})$/ to allow any kind of single-character delimiter. . = any character, whereas \. (escape+.) matches just the character ..
In my particular case I had to make the last 3 time characters (seconds) optional by using (.(\d{2}))? instead of the last .(\d{2}). I needed to match times such as both 11:23 and 11:23:55. Thanks for the head start!
2

Try something like this:

function checkDateTime(element){
  if (!Date.parse(element.value)){ 
     element.style.background = 'red'; 
     element.focus(); 
     return false; 
  } else { 
     element.style.background = 'white'; 
    return true; 
  }
}

function checkForm(form){
  return checkDateTime(form.mytxtfield01) && checkDateTime(form.mytxtfield02)
}

No regular expression; only the function Date.parse('...') is used.

Comments

0

You need to properly test the regular expression to make sure it matches the date format you want. This tool can help you debug the expression: http://regexpal.com/.

Alternatively since you are already using jQuery, you could try using a validation plugin such as http://formvalidator.net/.

2 Comments

Dates don't really follow a regular grammar, especially if you take leap years into account. Regular expressions are not the right tool for validating a date. Now a date-format, sure, but not the actual date.
I completely agree but if you check the OP's question: "I am trying to validate textbox with 'valid datetime format'"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.