Link to home
Start Free TrialLog in
Avatar of earwig75
earwig75

asked on

How can I validate date and time in one field?

I have a text box with a date/time picker, but the box is not read only. I need to use jquery or javascript to validate the date/time entered meets the following format: 09/19/2016 15:31

That is.. I need to validate input in the text box as mm/dd/yyyy [space] 24:hour time clock. Does anyone have experience with how I can do this? If so, do you have a code example? I'm thinking maybe a regular expression? Thank you.
ASKER CERTIFIED SOLUTION
Avatar of Kim Walker
Kim Walker
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of earwig75
earwig75

ASKER

Please forgive my ignorance, but why is there a comma after your first line? I need to set the date equal to the value of a field. Below is what I am using, but it fails. Can you help?

var testdate = document.forms["myForm"]["dateTimeField"].value,
    patt = /(0[1-9]|1[0-2])\/(0[1-9]|[12]\d|3[01])\/20\d\d (([01]\d|2[0-3]):[0-5]\d|24:00)/;
if (patt.test(testdate) ) {
    alert('Date format is correct!');
} else {
    alert('Incorrect date format. Please provide your date and time in mm/dd/20yy hh:mm 24-hour format.');
}

Open in new window

Nevermind, I just needed the regular expression. I got it to work by using the below, thank you very much!
$('#test').submit(function(){
    var val = $('#myBox').val();
    if(/(0[1-9]|1[0-2])\/(0[1-9]|[12]\d|3[01])\/20\d\d (([01]\d|2[0-3]):[0-5]\d|24:00)/.test(val) == false) {
      alert("test");  
        return false;
    }
}
);

Open in new window

The comma was to separate the two variables I was declaring, testdate and patt.

You are welcome.