Click here to Skip to main content
15,886,873 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.18.0/jquery.validate.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.18.0/additional-methods.js"></script>


$(document).ready(function () {

        $('#formsub').validate({ // initialize the plugin
            rules: {
                Email: {
                    required: true,
                    email: true
                },
                //field2: {
                //    required: true,
                //    minlength: 5
                //}
            }
        });

    });


What I have tried:

i requrid birthday validation.
i have datepicker and i have to validate if employee is less then 18 years then not allow. (give validation msg)

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.18.0/jquery.validate.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.18.0/additional-methods.js"></script>
Posted
Updated 20-Nov-18 18:24pm
v2
Comments
Jaydeep Shah 20-Nov-18 21:58pm    

You will need to create a custom routine to add a new Validation function. This will need to be after your two CDN calls and before you have your validation routine.
JavaScript
$.validator.addMethod("minAge", function(value, element, min) {
    var today = new Date();
    var birthDate = new Date(value);
    var age = today.getFullYear() - birthDate.getFullYear();
 
    if (age > min+1) { return true; }
 
    var m = today.getMonth() - birthDate.getMonth();
 
    if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) { age--; }
 
    return age >= min;
}, "You are not old enough!");

The next thing you will need to do is to incorporate this into your existing validation functions. Here is the new method
JavaScript
$("form").validate({
    rules: {
        dob: {
            required: true,
            minAge: 13
        }
    },
    messages: {
        dob: {
            required: "Please enter you date of birth.",
            minAge: "You must be at least 13 years old!"
        } 
    }
});


These script blocks were easy to find searching google for jQuery Validate Age
This came from the #1 result Check for a Minimum Age with jQuery Validation | Pete Mall[^]
 
Share this answer
 
You can try with this code.
<input type="text" id="dob" name="dob">

var today = new Date();
var dob = new Date($("#dob").val());
var age = Math.floor((today-dob) / (365.25 * 24 * 60 * 60 * 1000));
if(age < 18)
{
alert("Age should be minimum 18");
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900