Check date and time using javascript and regex

I am trying to check a text box with a valid date and time format. I need to check the data format in 24 hours format. So I enter the following text in the text box22.05.2013 11:23:22

But he still does not check the correctness. I am completely unfamiliar with regex. It is still I 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

+4
source share
3 answers

It is very difficult to check the date with a regular expression. How do you confirm, for example, on February 29? (it is difficult!)

Instead, I would use an inline object Date. It will always give a valid date. If you do:

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

, . , , . >59, ..

:

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/

+11
+1

- :

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)
}

; Date.parse('...').

0
source

All Articles