验证JavaScript中出生日期

发布于 2025-02-10 22:46:59 字数 449 浏览 2 评论 0原文

我想要出生日期的验证。我已经使用了新的日期方法,因此我不应该在今天之后获得日期。但是,即使我在今天之后插入日期也没有显示无效的日期。

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

I want the validation for date of birth. I have used new Date method so that i should not get date after today. But even though i insert date after today it doesn't show invalid 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");
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

路弥 2025-02-17 22:46:59

您可以我的代码:

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

You can you my code :

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");
        }
私藏温柔 2025-02-17 22:46:59

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

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

Your current code is good except for the second condition. It should be a timestamp comparison.

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");
}
吖咩 2025-02-17 22:46:59
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");
        }
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");
        }
半暖夏伤 2025-02-17 22:46:59

dateofbirth
未定义。尝试添加输入。

dateofbirth
is not defined. Try to add an input.

十年九夏 2025-02-17 22:46:59

主要问题是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. 您还应考虑LEAP年,而DOB计算中的此操作
  3. 始终对后端服务器进行检查DOB或将所有数据转换为UTC

The primary issue is that the dateofbirth variable is a type of string.

You should always compare two similar variable types to ensure the results are consistent.

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;


}

Considerations

  1. You should also set the time to be 00:00:00 before checking
  2. You should also consider leap year and such in DOB calculations
  3. Always check DOB against the backend server datetime or convert all datetimes to UTC
铃予 2025-02-17 22:46:59

在比较之前,请使用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");
}

Use the setHours function to set the hours, minutes, seconds and milliseconds to zero before comparison

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");
}
舂唻埖巳落 2025-02-17 22:46:59

您的dateofth变量是类型字符串的,而今天的日期是一个日期对象,因此当您比较dateofbirth是否大于当前日期。它将始终导致错误。为了解决此问题,您可以将日期构造函数传递给dateofth,该构造函数将其转换为日期对象,然后您可以将其转换为comapre。像这样:

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

Your dateofbirth variable is of type string whereas your today's date is a date object so when you are comparing whether dateofbirth is greater than current today's date or not. It will always result in false. To fix this you can pass your dateofbirth in Date constructor which will convert it into date object then you can comapre it. Like this:

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");
}
笙痞 2025-02-17 22:46:59

如果要将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日。

If you want to compare the DOB with the current date you need to turn it into a date object first:

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"}`));

As the last two test cases show, this is not yet "perfect" either: JavaScript accepts input like "1974-02-31" and will interpret it as "3 days after 28 February 1974", which is 3 March of that year.

白鸥掠海 2025-02-17 22:46:59

由于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');

Since dateOfBirth is a string and date is an object, they need to be converted to the same data type. Easiest type to compare (besides boolean) are numbers. We could Date.parse() each one as a timestamp:

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');

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文