客户侧出生日期使用JavaScript



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

  1. 输入模式,格式应仅接受DD/mm/yyyy
  2. 输入值在某些范围内
  3. leap年

我尝试将在线找到的解决方案与自己的代码结合在一起。当我尝试验证日期时,即使数据正确,也会显示错误消息。有人有解决方案吗?

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>

我不知道你为什么要这样做,你可以做另一个更轻松的方法。

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

最新更新