简体   繁体   English

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

[英]Client side date of birth validation using Javascript

I have 3 separate input fields for DOB. 我有3个单独的DOB输入字段。 My validation would check for: 我的验证将检查:

  1. input pattern, the format should only accept dd/mm/yyyy 输入格式,格式只能接受dd / mm / yyyy
  2. input values are within certain bounds 输入值在一定范围内
  3. leap years 闰年

I have tried combining a solution I found online with my own code. 我尝试将在网上找到的解决方案与自己的代码结合起来。 When I try to validate the date the error message is displayed even if the data is correct. 当我尝试验证日期时,即使数据正确,也会显示错误消息。 Does anyone have a solution for this? 有人对此有解决方案吗?

http://jsfiddle.net/noemitotos/5t9wboaq/10/ 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];
});

And my markup: 和我的标记:

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

I don't know why you want to do this you can do it another easier way. 我不知道您为什么要执行此操作,您可以使用另一种简单的方法来执行此操作。

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

then you can use Date function 然后您可以使用日期功能

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM