Javascript Date Validation For Mm/dd/yyyy Format In Asp.net
I want to validate BirthDate, which should be in 'mm/dd/yyyy' format, on the client side. I have tried it as following, but it is not working properly: $('#btnUpdateEditCB3').click
Solution 1:
Solution 2:
I recommend that you use the JavaScript Date() object along with regular expressions to validate a date. You can use a variant of this code as follows:
functionValidateCustomDate(d) {
var match = /^(\d{2})\/(\d{2})\/(\d{4})$/.exec(d);
if (!match) {
// pattern matching failed hence the date is syntactically incorrectreturnfalse;
}
var month = parseInt(match[1], 10) - 1; // months are 0-11, not 1-12var day = parseInt(match[2], 10);
var year = parseInt(match[3], 10);
var date = newDate(year, month, day);
// now, Date() will happily accept invalid values and convert them to valid ones// therefore you should compare input month/day/year with generated month/day/yearreturn date.getDate() == day && date.getMonth() == month && date.getFullYear() == year;
}
console.log(ValidateCustomDate("1/01/2011")); // falseconsole.log(ValidateCustomDate("01/1/2011")); // falseconsole.log(ValidateCustomDate("01/01/2011")); // trueconsole.log(ValidateCustomDate("02/29/2011")); // falseconsole.log(ValidateCustomDate("02/29/2012")); // trueconsole.log(ValidateCustomDate("03/31/2011")); // trueconsole.log(ValidateCustomDate("04/31/2011")); // false
Solution 3:
Is there any specific reason for not using datepicker formatting? Suggest using a jquery datepicker where you can set the formats.
Solution 4:
If you want to validate date in mm/dd/yyyy format using javascript you can use the following snippet of code.
txtdate is having textbox id
Consider the below code.
functionisValidDate(txtdate) {
var txtDate = "#" + txtdate;
var dateString = $(txtDate).val();
var date_regex = /^(0[1-9]|1[0-2])\/(0[1-9]|1\d|2\d|3[01])\/(19|20)\d{2}$/;
if (!(date_regex.test(dateString))) {
alert("Date Must Be in mm/dd/yyyy format");
}}
Post a Comment for "Javascript Date Validation For Mm/dd/yyyy Format In Asp.net"