Home > Back-end >  validation of date of birth in javascript
validation of date of birth in javascript

Time:06-25

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

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

dateofbirth is not defined. Try to add an input.

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

You can you my code :

    dateofbirth = "2000-06-12"
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");
        }

CodePudding user response:

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.

CodePudding user response:

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

  • Related