Reputation: 15299
In my form, a user can enter the date like this: 220875
(day, month, year).
Once they entered the details, I would like to test that the date is valid:
How would I find out whether or not the values are correct and matching?
here is my attempt: (excerpt)
DateIsOk:function(value) { //220875 for example
var formatValue = value.match(/.{1,2}/g), //splting as 22 08 75
fieldDate = parseInt(formatValue[0]), //converting to num
fieldMonth = parseInt(formatValue[1]),
fieldYear = parseInt(formatValue[2]),
dayobj = new Date();
//test need to go here...
}
If it helps, here is a Live Demo.
Upvotes: 1
Views: 1695
Reputation: 4883
If you don't mind using momentjs
as @hVostt suggested, you could try modifying your DateIsOk()
validation function like this:
...
dateParts : ["years", "months", "days", "hours", "minutes", "seconds", "milliseconds"],
DateIsOk:function(value) {
var dayobj = moment(value, "DDMMYY");
if (dayobj.isValid()) {
this.errorHandler(true);
return true;
}
else {
this.errorHandler('Invalid ' + this.dateParts[dayobj.invalidAt()]);
return false;
}
}
...
Here's the updated Live Demo
Upvotes: 1
Reputation: 1681
Please try Moment.js and his validation functions:
http://momentjs.com/docs/#/parsing/is-valid/
moment([2014, 25, 35]).isValid();
moment("2014-25-35").isValid();
Upvotes: 0
Reputation: 843
It seems you use the DD/MM/YYYY format.
So you can easily use this ready-to-use code: http://www.qodo.co.uk/blog/javascript-checking-if-a-date-is-valid/
JavaScript
// Checks a string to see if it in a valid date format
// of (D)D/(M)M/(YY)YY and returns true/false
function isValidDate(s) {
// format D(D)/M(M)/(YY)YY
var dateFormat = /^\d{1,4}[\.|\/|-]\d{1,2}[\.|\/|-]\d{1,4}$/;
if (dateFormat.test(s)) {
// remove any leading zeros from date values
s = s.replace(/0*(\d*)/gi,"$1");
var dateArray = s.split(/[\.|\/|-]/);
// correct month value
dateArray[1] = dateArray[1]-1;
// correct year value
if (dateArray[2].length<4) {
// correct year value
dateArray[2] = (parseInt(dateArray[2]) < 50) ? 2000 + parseInt(dateArray[2]) : 1900 + parseInt(dateArray[2]);
}
var testDate = new Date(dateArray[2], dateArray[1], dateArray[0]);
if (testDate.getDate()!=dateArray[0] || testDate.getMonth()!=dateArray[1] || testDate.getFullYear()!=dateArray[2]) {
return false;
} else {
return true;
}
} else {
return false;
}
}
Upvotes: 1
Reputation: 121
The js regexp maybe like this
/([0-2][0-9]|3[01])(0[1-9]|1[0-2])(\d{2})/
Upvotes: 0