客户端使用Javascript验证出生日期

时间:2017-11-23 11:34:22

标签: javascript validation

我有30个单独的DOB输入字段。我的验证将检查:

  1. 输入模式,格式应该只接受dd / mm / yyyy
  2. 输入值在特定范围内
  3. 闰年
  4. 我尝试将我在网上找到的解决方案与我自己的代码结合起来。当我尝试验证日期时,即使数据正确,也会显示错误消息。有人有解决方案吗?

    http://jsfiddle.net/noemitotos/5t9wboaq/10/

    $(".btn").on ('click', function() {
      // Combine date
      var day = $('#dob_day').val();
      var month = $('#dob_month').val();
      var year = $('#dob_year').val();
      var dateString = day + "/" + month + "/" + year;
      console.log(dateString);
    
      // First check for the pattern
      if (!/^(0?[1-9]|[12][0-9]|3[01])[\/\-](0?[1-9]|1[012])[\/\-]\d{4}$/.test(dateString)) {
        console.log('false pattern');
        return false;
      }
    
      // Check the ranges of month and year
      if (year < 1911 || year > 2011 || month == 0 || month > 12) {
        console.log('incorrect month/year ranges');
        return false;
      }
    
      var monthLength = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
    
      // Adjust for leap years
      if (year % 400 == 0 || (year % 100 != 0 && year % 4 == 0))
        monthLength[1] = 29;
    
      // Check the range of the day
      return day > 0 && day <= monthLength[month - 1];
    });
    

    我的标记:

    <input type="text" value="" placeholder="DD" name="customer[dob]" id="dob_day" class="large" /> /
    <input type="text" value="" placeholder="MM" name="customer[dob]" id="dob_month" class="large" /> /
    <input type="text" value="" placeholder="YYYY" name="customer[dob]" id="dob_year" class="large" />
    <button class="btn" type="submit" value="">Validate</button>
    

1 个答案:

答案 0 :(得分:0)

我不知道你为什么要这样做,你可以采用另一种更简单的方式。

var day = $('#dob_day').val();
var month = $('#dob_month').val();
var year = $('#dob_year').val();
var dateString = month + "/" + day + "/" + year;

然后你可以使用日期功能

if(new Date(dateString) != "Invalid Date"){
    here goes your other logic
}else{
    return false;
}