views:

49

answers:

5

Hi, I have one web application, in this i have to validate one date field of format like mm/dd/yyyy. I searched in the net but i didn't get the proper one. Please help me by providing the new function or by correcting on my code. My code is shown below.. I had called this JS function at onblur event..

function isValidDate() {

var re = new RegExp('^(0[1-9]|[12][0-9]|3[01])/(0[1-9]|1[012])/(19|20)dd$');

if (form1.txtDateOfOccurance.value != '' && !form1.txtDateOfOccurance.value.match(re)) {
    alert("Invalid date format: " + form1.txtDateOfOccurance.value);
    form1.txtDateOfOccurance.value = "";
    form1.txtDateOfOccurance.focus();
    isEnable();
    return false;
}

}

Thanks in advance..

+2  A: 

Have a look at http://www.smartwebby.com/DHTML/date_validation.asp, first search result when googling for "javascript date validation"..

kb
A: 

I'd just try parsing the string as a Date object and check the result (assuming you only need to know if it's a valid date or not):

var myDate = Date.parse(form1.txtDateOfOccurance.value);
if(isNaN(myDate)){ 
    // it's not a real date
}
inkedmn
A: 
function IsValidDate(str) {
    var str2=""; 
    var date = new Date(str); 
    str2 = (date.getMonth()+1) + "/" 
               + date.getDay() + "/" 
               + (date.getYear()+1900);

    return (str == str2);
}
signetro
A: 

Here's the regex you want.


var re = /^(0[1-9]|1[0-2])\/(0[1-9]|[1-3]\d)\/((19|20)\d\d)$/

Though you are probably better off, as inkedmn suggests validating by parsing the input, since MM/dd/yyyy is a recognized date format via Date.parse.

Tracker1
A: 

You can use:

function checkdate(input){
var validformat=/^\d{2}\/\d{2}\/\d{4}$/ //Basic check for format validity
var returnval=false;
if (!validformat.test(input.value))
alert("Invalid Date Format. Please correct and submit again.");
else{ //Detailed check for valid date ranges
var monthfield=input.value.split("/")[0];
var dayfield=input.value.split("/")[1];
var yearfield=input.value.split("/")[2];
var dayobj = new Date(yearfield, monthfield-1, dayfield);
if ((dayobj.getMonth()+1!=monthfield)||(dayobj.getDate()!=dayfield)||(dayobj.getFullYear()!=yearfield))
alert("Invalid Day, Month, or Year range detected. Please correct and submit again.");
else
returnval=true;
}
if (returnval==false) input.select()
return returnval;
}
Kangkan