Re: Regex Date Validation
This works without leap year
Code:
^((0?[13578]|10|12)(-|\/)(([1-9])|(0[1-9])|([12])([0-9]?)|(3[01]?))(-|\/)((19|20)([0-9])(\d{1})|(20)([01])(\d{1})|([8901])(\d{1}))
|
(0?[2469]|11)(-|\/)(([1-9])|(0[1-9])|([12])([0-9]?)|(3[0]?))(-|\/)((19|20)([0-9])(\d{1})|(20)([01])(\d{1})|([8901])(\d{1})))$
Re: Regex Date Validation
HTML
Code:
<form>
<p>Enter date</p>
<input type="text" id="test1" value="22.05.2013 11:23:22"/>
</form>
JS
Code:
$(document).ready(function(){
$('#test1').blur(function(){
if (is_valid_date($(this).val())) {
$(this).css('background', '#dfd');
} else {
$(this).css('background', '#fdd');
}
});
});
function is_valid_date(value) {
// capture all the parts
var matches = value.match(/^(\d{2})\.(\d{2})\.(\d{4}) (\d{2}):(\d{2}):(\d{2})$/);
if (matches === null) {
return false;
} 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
) {
return false;
} else {
return true;
}
}
}
Try like this!!!
Re: Regex Date Validation
I would not try to reinvent the wheel. MomentJS is a reliable library that allows you to parse, validate, manipulate, and display dates/times in JavaScript.
In this case, it would be as simple as:
Code:
const inputBlur = function(e) {
const value = e.target.value;
const conversion = moment(value);
console.log(`${value} is valid: ${conversion.isValid()}`);
}
Fiddle: Live Demo
Re: Regex Date Validation
You should always specify a format when using momentJS's isValid(), as well as specifying strict, otherwise you can have unexpected outcomes.
For example, your example above would return true for the value of
"it is 12/25/25"
So you would need to do a conversion for each format you expect, but for just MM/DD/YYYY it would instead be:
Code:
const inputBlur = function(e) {
const value = e.target.value;
const conversion = moment(value, 'MM/DD/YYYY', true);
console.log(`${value} is valid: ${conversion.isValid()}`);
}
Re: Regex Date Validation
That's good to know, thank you kfcSmitty.