繁体   English   中英

在javascript中验证出生日期

[英]validation of date of birth in javascript

我想要验证出生日期。 我使用了新的 Date 方法,所以我不应该在今天之后得到日期。 但即使我在今天之后插入日期,它也不会显示无效日期。

var pattern = /^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])$/
var date= new Date();
if (dateofbirth == "" || dateofbirth == null||!pattern.test(dateofbirth)) {
    alert("invalid date of birth should in yyyy-mm-dd");
    return false;
}
else if(dateofbirth >date){
    alert("invalid date");
    return false;
}
else{
    alert("valid date");
}

你可以我的代码:

var validation = /^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])$/
     var date= new Date();
        if (dateofbirth == "" || dateofbirth == null||!validation.test(dateofbirth)) {
            alert("Date of Birth is Invalid it should in yyyy-mm-dd");
            return false;
        }
        else if(dateofbirth >date.getFullYear()){
            alert("Invaid Date");
            return false;
        }
        else{
            alert("Your Date is Valid");
        }
var pattern = /^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])$/
     var date= new Date();
        if (dateofbirth == "" || dateofbirth == null||!pattern.test(dateofbirth)) {
            alert("invalid date of birth should in yyyy-mm-dd");
            return false;
        }
        else if(dateofbirth >date.getFullYear()){
     // get full year give current year you can compare with that year 
    // to date of birth
            alert("invalid date");
            return false;
        }
        else{
            alert("valid date");
        }

dateofbirth 尝试添加输入。

您当前的代码很好,除了第二个条件。 应该是时间戳比较。

var pattern = /^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])$/
var date= new Date();
if (dateofbirth == "" || dateofbirth == null||!pattern.test(dateofbirth)) {
    alert("invalid date of birth should in yyyy-mm-dd");
    return false;
}
else if(new Date(dateofbirth).getTime() > date.getTime()){
    alert("invalid date");
    return false;
}
else{
    alert("valid date");
}

主要问题是dateofbirth变量是一种类型的string

您应该始终比较两个相似的变量类型以确保结果一致。

const pattern = /^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])$/
dateofbirth = "2022-12-31"; // YYYY-MM-DD
isDOBValid(dateofbirth);

function isDOBValid(dobString) {
         var date= new Date();
            if (dobString == "" || dobString == null||!pattern.test(dobString)) {
                console.log("invalid date of birth should in yyyy-mm-dd");
                return false;
            }
            var dobDate = new Date(dobString);
            console.log("Checking: ", dobDate.toLocaleDateString());
                        
            if(dobDate > date) { // Check if DOB is after today
                console.log("invalid date");
                return false;
            }
            
  console.log("valid date");
  return true;


}

注意事项

  1. 您还应该在检查之前将时间设置为 00:00:00
  2. 您还应该在 DOB 计算中考虑闰年等
  3. 始终根据后端服务器日期时间检查 DOB 或将所有日期时间转换为 UTC

使用setHours函数将小时、分钟、秒和毫秒设置为零,然后再进行比较

var pattern = /^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])$/
var date= new Date();

date.setHours(0,0,0,0);
dateofbirth.setHours(0,0,0,0);

if (dateofbirth == "" || dateofbirth == null||!pattern.test(dateofbirth)) {
  alert("invalid date of birth should in yyyy-mm-dd");
  return false;
} else if(dateofbirth > date){
// get full year give current year you can compare with that year 
// to date of birth
   alert("invalid date");
   return false;
} else{
   alert("valid date");
}

您的 dateofbirth 变量是字符串类型,而您今天的日期是一个日期对象,因此当您比较 dateofbirth 是否大于当前日期时。 它总是会导致错误。 要解决此问题,您可以在 Date 构造函数中传递您的 dateofbirth,它将其转换为日期对象,然后您可以对其进行比较。 像这样:

var pattern = /^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])$/
var date= new Date();
if (dateofbirth == "" || dateofbirth == null||!pattern.test(dateofbirth)) {
    alert("invalid date of birth should in yyyy-mm-dd");
}
else if(new Date(dateofbirth) >date){
    alert("invalid date");
}
else{
    alert("valid date");
}

如果要将 DOB 与当前日期进行比较,则需要先将其转换为日期对象:

 function invalidDOB(dateofbirth){ var pattern = /^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])$/, dob; var date= new Date(); if (dateofbirth == "" || dateofbirth == null||!pattern.test(dateofbirth)) { return "Invalid date format, should be: yyyy-mm-dd"; } else if((dob=new Date(dateofbirth))>date){ return "The date is in the future: "+dob.toLocaleString(); } else{ return undefined; } } const test=["01.02.1974","1974-02-01","02/01/1974","1 Feb 1974","1974-02-31","2023-02-31"]; test.forEach(d=>console.log(`${d}: ${invalidDOB(d)??"OK"}`));

正如最后两个测试用例所示,这也不是“完美的”:JavaScript 接受像“1974-02-31”这样的输入,并将其解释为“1974 年 2 月 28 日之后的 3 天”,即当年的 3 月 3 日。

由于dateOfBirth是一个字符串,而date是一个对象,因此需要将它们转换为相同的数据类型。 最容易比较的类型(除了布尔值)是数字。 我们可以将Date.parse()每一个作为时间戳:

let birth = Date.parse(dateOfBirth);
let now = Date.parse(date.toLocaleDateString());

 function validateDateOfBirth(dateOfBirth) { const pattern = /^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])$/ let date= new Date(); let birth = Date.parse(dateOfBirth); console.log(`Date of Birth Timestamp: ${birth}`); let now = Date.parse(date.toLocaleDateString()); console.log(`Current Timestamp: ${now}`); if (dateOfBirth == "" || dateOfBirth == null||!pattern.test(dateOfBirth)) { console.log("Required format is yyyy-mm-dd"); return false; } else if (birth > now){ console.log("Invalid date"); return false; } else { console.log("Valid date"); } } validateDateOfBirth('1972-05-12'); validateDateOfBirth('2032-02-29');

暂无
暂无

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

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