首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Javascript错误地验证日期

Javascript错误地验证日期
EN

Stack Overflow用户
提问于 2017-10-31 15:15:20
回答 3查看 69关注 0票数 1

我编写了一个函数来检查日期是否有效。

我只写了一小部分

这个函数不工作,我找不到错误,你能帮忙吗?

我可以看到,因为数字29不在数组中,所以它不起作用,但是我搞不懂如何使它工作。

代码语言:javascript
复制
function isValidDate() {
  var dateformat = /^(0?[1-9]|[12][0-9]|3[01])[-](0?[1-9]|1[012])[-]\d{4}$/;

  var readDate = document.getElementById("myDate").value;

  if (readDate.length <= 10) {
    <!--debug-->
    //console.log(readDate);

    /* split date into DD-MM-YYYY format */
    var splitDate = readDate.split('-');

    var day = splitDate[0];

    var month = splitDate[1];

    var year = splitDate[2];

    /* DEBUG - print split date into DD-MM-YYYY format */
    console.log('day ' + day);
    console.log('month ' + month);
    console.log('year ' + year);

    // Create list of days of a month [assume there is no leap year by default]  
    var ListofDays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

    //if month is between 1-12
    if (month == 1 || month < 13) {
      //check for invalid month
      if (month == 00) {
        console.log('0 - Invalid MONTH format!');
        return 0;
      }

      //check for invalid day
      if (day == 00) {
        console.log('0 - Invalid DAY format!');
        return 0;
      }

      //check DAY exists in the MONTH
      if (day > ListofDays[month - 1]) {
        console.log('1 - Invalid DATE format!');
        return 0;
      } else {
        console.log('1 - Valid DATE format!');
        return 1
      }
    } else {
      console.log("Invalid MONTH");
      return 0;
    }

    //check for leap year
    if (year % 4 === 0 && year % 100 !== 0) {
      console.log('The year ' + year + ' is a leap year.');
      return 1;
    } else if (year % 4 === 0 && year % 100 === 0 && year % 400 === 0) {
      console.log('The year ' + year + ' is a leap year.');
      return 1;
    } else {
      console.log('The year ' + year + ' is NOT a leap year');
      return 0;
    }
  } else {
    console.log("Invalid DATE length")
  }
}


/*    This is the only bit I did not write:
    
    	if (day > ListofDays[month-1])  
    	{  
        console.log('1 - Invalid DATE format!');  
        return 0;  
    	} 
    	else
        {
        console.log('1 - Valid DATE format!');  
        return 1
    }

*/
代码语言:javascript
复制
<p>Input a date and check it's in a)correct format and b)it is a valid date</p>

<input type="text" id="myDate" placeholder="DD-MM-YYYY"> <br><br>

<button type="button" onclick="isValidDate()"> Check Date </button>

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2017-10-31 16:10:06

  1. 根据regex测试日期,您必须减少测试
  2. 当您想要继续时不要返回

这里有一个解决方案,使代码尽可能接近您想要做的事情。我已经在注释中建议使用日期对象的更简单的解决方案,其他人已经对其进行了详细阐述。

代码语言:javascript
复制
function showError(str) {
  console.log(str)
  return false;
}

function isValidDate() {
  var dateformat = /^(0?[1-9]|[12][0-9]|3[01])[-](0?[1-9]|1[012])[-]\d{4}$/;

  var readDate = document.getElementById("myDate").value;

  if (readDate.length != 10) return showError("Invalid DATE length") // not correct length
  console.log(dateformat.test(readDate));

  if (!dateformat.test(readDate)) {
    return showError("Invalid DATE format") // not matching regex
  }

  /* split date into DD-MM-YYYY format */
  var splitDate = readDate.split('-');

  var day = splitDate[0];
  var month = splitDate[1];
  var year = splitDate[2];

  /* DEBUG - print split date into DD-MM-YYYY format */
  console.log('day ' + day);
  console.log('month ' + month);
  console.log('year ' + year);

  // Create list of days of a month [assume there is no leap year by default]  
  var ListofDays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

  //if month is not between 1-12
  if (month <= 0 || month > 12) {
    return showError('0 - Invalid MONTH format!');
  }

  var isLeap = false;
  //check for leap year
  if (year % 4 === 0 && year % 100 !== 0) {
    console.log('The year ' + year + ' is a leap year.');
    isLeap = true;
  } else if (year % 4 === 0 && year % 100 === 0 && year % 400 === 0) {
    console.log('The year ' + year + ' is a leap year.');
    isLeap = true;
  } else {
    console.log('The year ' + year + ' is NOT a leap year');
  }

  //check DAY exists in the MONTH
  var testDay = ListofDays[month - 1]; // array starts at 0
  // testDay += isLeap ? 1 : 0; // add one to testDay using ternary operator
  if (isLeap) testDay++; // less code, does the same as above
  if (day > testDay) {
    return showError('1 - Invalid DATE format!');
  }

  console.log('1 - Valid DATE format!');
  // You can return true here if you want


}
代码语言:javascript
复制
<p>Input a date and check it's in a)correct format and b)it is a valid date</p>

<input type="text" id="myDate" placeholder="DD-MM-YYYY"> <br><br>

<button type="button" onclick="isValidDate()"> Check Date </button>

票数 1
EN

Stack Overflow用户

发布于 2017-10-31 15:36:03

把这些都扔掉。

代码语言:javascript
复制
<input type="date" />

工作完成了。

或者,由于您指定了格式,所以可以这样做:

代码语言:javascript
复制
var input = document.getElementById("myDate").value;
var parts = input.split("-");
var date = new Date(parts[2],parts[1]-1,parts[0]);
return date.getFullYear() == parts[2]
    && date.getMonth() == parts[1]-1
    && date.getDate() == parts[0];

这是因为JavaScript会“修正”日期,如果它超出了有效的界限(例如。1月32号被更正为2月1日),所以只要看看它收到日期后是否有任何变化。

票数 0
EN

Stack Overflow用户

发布于 2017-10-31 15:57:05

代码语言:javascript
复制
function validate(value) {
  var v = false;
  if (value) {
    var r = value.match(/([0-9]{1,2}).?([0-9]{1,2}).?([0-9]{4})/);
    
    if (r) {
      var day1 = parseInt(r[1]);
      var month1 = parseInt(r[2]);
      var year1 = parseInt(r[3]);

      var d = new Date(year1, month1 - 1, day1);

      var day2 = d.getDate();
      var month2 = d.getMonth() + 1;
      var year2 = d.getFullYear();

      v = day1    == day2   &&
          month1  == month2 &&
          year1   == year2;
    }
  }
  
  return v;
}
代码语言:javascript
复制
<input type="text" id="toCheck" />
<button onclick="console.log(validate(document.getElementById('toCheck').value))">Check</button>

您可以尝试使用任何分隔符,这只是一个例子(我使用了一个技巧来检查一个真正的日期)。您可以修改此函数以供个人使用。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47038787

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档