Age Validation in jQuery

    [javascript]
    <!DOCTYPE html>
    <html>
    <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
    </head>
    <body><form name="demoForm" id="demoForm" action="">
    <input type="hidden" name="requiredAge" id="requiredAge" value="18">
    <h4>Enter Birth Date</h4>
    <p>Day: <input type="text" name="birthDay" id="birthDay" value=""></p>
    <p>Month: <input type="text" name="birthMonth" id="birthMonth" value=""></p>
    <p>Year: <input type="text" name="birthYear" id="birthYear" value=""></p>
    <input type="submit" name="submit" value="Submit">
    </form>

    <script language="JavaScript1.2">
    $("#demoForm").submit(function(){
    var day = $("#birthDay").val();
    var month = $("#birthMonth").val();
    var year = $("#birthYear").val();
    var age = $("#requiredAge").val();
    if (day == "" || month == "" || year == "") {
    alert("You must enter all fields.");
    return false;
    }
    var mydate = new Date();
    mydate.setFullYear(year, month-1, day);

    var currdate = new Date();
    currdate.setFullYear(currdate.getFullYear() – age);
    if ((currdate – mydate) < 0){
    alert("Sorry, only persons over the age of " + age + " may enter this site");
    return false;
    }
    alert("Success! Submitting Form…");
    return true;
    });
    </script>
    </body>
    </html>
    [/javascript]

    Tags:

    One Reply to Age Validation in jQuery

    1. Emeka says:

      Nice Validation snippet however, i displaying error messages on a div instead of using alert.

    Leave a Reply