首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用Javascript验证客户端出生日期

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

Stack Overflow用户
提问于 2017-11-23 11:34:21
回答 1查看 311关注 0票数 0

我为道布有三个独立的输入字段。我的验证将检查:

  1. 输入模式,格式应只接受dd/mm/yyyy
  2. 输入值在一定范围内。
  3. 闰年

我尝试将我在网上找到的解决方案与我自己的代码结合起来。当我试图验证日期时,即使数据是正确的,也会显示错误消息。有人有办法解决这个问题吗?

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

代码语言:javascript
复制
$(".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];
});

我的标记是:

代码语言:javascript
复制
<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>
EN

回答 1

Stack Overflow用户

发布于 2017-11-23 12:00:56

我不知道你为什么要这么做--你可以用另一种更简单的方法来做。

代码语言:javascript
复制
var day = $('#dob_day').val();
var month = $('#dob_month').val();
var year = $('#dob_year').val();
var dateString = month + "/" + day + "/" + year;

然后可以使用日期函数。

代码语言:javascript
复制
if(new Date(dateString) != "Invalid Date"){
    here goes your other logic
}else{
    return false;
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47454558

复制
相关文章

相似问题

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