How to Create Age Validation with jQuery?

Estimated read time 2 min read

To create age validation with jQuery, you can compare the user’s input to a minimum age requirement and show an error message if the user is too young. Here’s an example:

HTML code:

<label for="birthdate">Birthdate:</label>
<input type="date" id="birthdate">
<span id="age-error" style="color:red;display:none;">You must be at least 18 years old.</span>

In this example, we have an HTML label element and an input element with the ID “birthdate”. We also have a span element with the ID “age-error” that will be used to display an error message if the user is too young.

jQuery code:

$(document).ready(function(){
	var minimumAge = 18;

	$("#birthdate").change(function(){
		var birthdate = new Date($(this).val());
		var age = new Date(Date.now() - birthdate.getTime()).getUTCFullYear() - 1970;

		if(age < minimumAge){
			$("#age-error").show();
		}
		else{
			$("#age-error").hide();
		}
	});
});

In this example, we use the $() function to select the input element with the ID “birthdate”. We also define a minimumAge variable, which is set to 18 in this example.

We use the change() method to listen for changes to the birthdate input field. When the input field changes, we create a new Date object from the input value using the new Date() constructor. We then calculate the user’s age by subtracting the birthdate from the current date and getting the year difference using the getUTCFullYear() method.

Finally, we compare the user’s age to the minimumAge variable, and show or hide the error message using the show() and hide() methods of the $("#age-error") element.

This code ensures that the user cannot submit the form if they are too young, and shows an error message to inform them of the age requirement.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply