Javascript 错误地验证了日期

标签 javascript

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

除了一小部分我都写了

该功能不起作用,我找不到错误,您能帮忙吗?

我可以看到因为数字 29 不在数组中所以它不起作用但是我很困惑如何让它工作

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
    }

*/
<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. 根据您必须减少测试的正则表达式测试日期
  2. 当你想继续的时候不要回来

这是一个使代码尽可能接近您想要执行的操作的解决方案。使用日期对象的更简单的解决方案我已经在评论中提出并已被其他人详细阐述

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


}
<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>

关于Javascript 错误地验证了日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47038787/

相关文章:

javascript - 用于替换两个字符(包括字符)之间的字符串的正则表达式

javascript - 控制何时以 Angular 进行验证

javascript - 优化React中的功能。有 setState key 作为 Prop 吗?

javascript - 如何使用 JS 检测用户对 phonegap 的触摸

javascript - 该功能在 chrome 中运行良好,但在 IE 和 Firefox 中运行不佳

javascript - JSON 未捕获类型错误

javascript - 向回调函数添加额外的参数

javascript - 无法将修改后的字符串推送到 javascript 数组

javascript - 数组内的简单加法

javascript - 如何捕获 Bootstrap 导航栏下拉事件?