How to validate DOB in Javascript?

by cassandra , in category: JavaScript , a year ago

How to validate DOB in Javascript?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by marcella.kautzer , a year ago

@cassandra 

To validate the date of birth (DOB) in JavaScript, you can use the following approach:

  1. First, split the DOB string into three parts: the day, month, and year.
  2. Then, convert the month and day into integers and make sure they are within the correct range. For example, the month should be between 1 and 12, and the day should be between 1 and the number of days in the month.
  3. Finally, check that the year is a valid year. You can do this by checking if it is greater than or equal to the current year, or if it is a leap year if necessary.


Here's some example code that demonstrates this approach:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
function validateDOB(dob) {
  // Split the DOB string into its parts
  var parts = dob.split('/');
  var day = parseInt(parts[0], 10);
  var month = parseInt(parts[1], 10);
  var year = parseInt(parts[2], 10);

  // Check that the month is between 1 and 12
  if (month < 1 || month > 12) {
    return false;
  }

  // Check that the day is between 1 and the number of days in the month
  var maxDays = 31;
  if (month == 4 || month == 6 || month == 9 || month == 11) {
    maxDays = 30;
  } else if (month == 2) {
    maxDays = 28;
    if (year % 4 == 0) {
      maxDays = 29;
    }
  }
  if (day < 1 || day > maxDays) {
    return false;
  }

  // Check that the year is valid
  var currentYear = new Date().getFullYear();
  if (year < 1900 || year > currentYear) {
    return false;
  }

  return true;
}


You can then use this function to validate a DOB like this:

1
2
3
4
5
if (validateDOB('31/12/2000')) {
  console.log('Valid DOB');
} else {
  console.log('Invalid DOB');
}


Member

by antone , 4 months ago

@cassandra 

This code will check for the validity of the date of birth provided. It checks that the month is between 1 and 12, the day is between 1 and the maximum number of days in the month, and the year is between 1900 and the current year.


If the date of birth is valid, the function will return true. Otherwise, it will return false. You can replace the console.log statements with your desired logic or error messages.


Note: This code assumes that the date of birth is provided in the "dd/mm/yyyy" format. If you are using a different format, you will need to modify the code accordingly.