0

我尝试使用以下代码验证日期:-

    function d(id){
 var n= document.getElementById(id);
 var re=/^(?:(0[1-9]|1[012])[\- \/.](0[1-9]|[12][0-9]|3[01])[\- \/.](19|20)[0-9]{2})$/;
  if (re.test(n.value))
  {
     n.style.backgroundColor="#52F40C";

  }
  else
  {
    window.alert("Invalid date");
               n.style.backgroundColor="#F40C0C";
               n.focus();
               n.value="";

  }
}

但它不起作用。这段代码有什么问题?

4

2 回答 2

1

尝试这个

 function isValidDate(subject){
  if (subject.match(/^(?:(0[1-9]|1[012])[\- \/.](0[1-9]|[12][0-9]|3[01])[\- \/.](19|20)[0-9]{2})$/)){
    return true;
  }else{
    return false;
  }
}
于 2013-01-23T05:35:22.750 回答
-1

尝试使用此功能

function isDate(txtDate, separator) {
var aoDate,           // needed for creating array and object
    ms,               // date in milliseconds
    month, day, year; // (integer) month, day and year
// if separator is not defined then set '/'
if (separator === undefined) {
    separator = '/';
}
// split input date to month, day and year
aoDate = txtDate.split(separator);
// array length should be exactly 3 (no more no less)
if (aoDate.length !== 3) {
    return false;
}
// define month, day and year from array (expected format is m/d/yyyy)
// subtraction will cast variables to integer implicitly
month = aoDate[0] - 1; // because months in JS start from 0
day = aoDate[1] - 0;
year = aoDate[2] - 0;
// test year range
if (year < 1000 || year > 3000) {
    return false;
}
// convert input date to milliseconds
ms = (new Date(year, month, day)).getTime();
// initialize Date() object from milliseconds (reuse aoDate variable)
aoDate = new Date();
aoDate.setTime(ms);
// compare input date and parts from Date() object
// if difference exists then input date is not valid
if (aoDate.getFullYear() !== year ||
    aoDate.getMonth() !== month ||
    aoDate.getDate() !== day) {
    return false;
}
// date is OK, return true
return true;

}

于 2013-01-23T05:36:53.247 回答