Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Date Validation ( DD/MM/YYYY) & Age Checking

I've started to work on Javascript recently. What I am testing is checking the DoB in valid format. Next step will be checking the age.

What my HTML code includes is below

<form name="ProcessInfo" action="#" method="POST" enctype="multipart/form-data" target="_self" onsubmit="return checkForm();">
.
.
.
.
<br>
<label for="txtDOB">Date of Birth:* </label>
<input id="txtDOB" type="text" name="txtDOB" size="12">
format: ##/##/####
<br>
.
.
.
</form>
.
.

and I did the following in my .js file

var errMessage = "";

function checkForm() {
    validateName();
    validateSurname();
    carSelect();
    validateDOB();

    if (errMessage == "") {
    } else {
        alert(errMessage);
    }
}

...

function validateDOB()
{
    var dob = document.forms["ProcessInfo"]["txtDOB"].value;
    var pattern = /^([0-9]{2})-([0-9]{2})-([0-9]{4})$/;
    if (dob == null || dob == "" || !pattern.test(dob)) {
        errMessage += "Invalid date of birth\n";
        return false;
    }
    else {
        return true
    }
}

I tried to check if its valid with regular expression but I always get an alert even if I type the date correctly. And how can I seperate the DD / MM / YYYY to calculate the age?

like image 203
A. Mesut Konuklar Avatar asked Nov 06 '13 18:11

A. Mesut Konuklar


People also ask

How do you check if a string is a valid date in JavaScript?

Using the Date. One way to check if a string is date string with JavaScript is to use the Date. parse method. Date. parse returns a timestamp in milliseconds if the string is a valid date.


2 Answers

If you want to use forward slashes in the format, the you need to escape with back slashes in the regex:

var pattern =/^([0-9]{2})\/([0-9]{2})\/([0-9]{4})$/;

http://jsfiddle.net/P9TER/

like image 50
Drahcir Avatar answered Oct 21 '22 02:10

Drahcir


Using pattern and check validate:

var input = '33/15/2000';

var pattern = /^((0[1-9]|[12][0-9]|3[01])(\/)(0[13578]|1[02]))|((0[1-9]|[12][0-9])(\/)(02))|((0[1-9]|[12][0-9]|3[0])(\/)(0[469]|11))(\/)\d{4}$/;

alert(pattern.test(input));
like image 41
rung Avatar answered Oct 21 '22 03:10

rung