Reputation: 127
I'm trying to add Date validation to a HTML form. I want the date entered to be in the format HH:MM:SS
not HH:MM
.
If I enter date in the wrong format (e.g. HH:MM
) then an Alert should show saying:
"Date time format should be HH:MM:SS."
Please can you help me to correct my code so that it does this?
Here is my code in JavaScript:
if (date.match(regex pattern)) {
alert("Valid date");
} else {
alert("Invalid date: date should be in HH:MM:SS format!");
}
What is the correct way to validate the Time entered?
Upvotes: 2
Views: 4024
Reputation: 2114
This test HH:MM:SS pattern without testing about real hours, minutes and seconds:
HTML Code:
<form onsubmit="return validate()">
<input type="text" id="date" />
<input type="submit" />
</form>
Javascript code:
function validate() {
var date = document.getElementById("date").value;
if (date.match(/^[0-9]{2}:[0-9]{2}:[0-9]{2}$/)) {
alert("Valid date");
} else {
alert("Invalide date: dat should be in HH:MM:SS format!");
}
return false;
}
You can try it online here: http://jsfiddle.net/OscarGarcia/fow3htwz/1/
Remember: number of seconds and minutes are not tested! Someone could try to introduce this incorrect time: 43:87:91 and will (bad) pass the pattern!
This code works like a charm :) http://jsfiddle.net/OscarGarcia/fow3htwz/2/
function validate() {
var date = document.getElementById("date").value;
if (date.match(/^([0-1][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]$/)) {
alert("Valid date");
} else {
alert("Invalide date: dat should be in HH:MM:SS format!");
}
return false;
}
Try it online: http://jsfiddle.net/OscarGarcia/fow3htwz/4/
function validate() {
var date = document.getElementById("date").value;
var pattern = /^([0-1][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]$/;
if (pattern.test(date)) {
alert("Valid date");
} else {
alert("Invalide date: dat should be in HH:MM:SS format!");
}
return false;
}
Best regards.
Upvotes: 2