Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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
";
        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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
409 views
Welcome To Ask or Share your Answers For Others

1 Answer

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/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...