Before writing jQuery code we need to do some basic steps
1. Sample HTML code
Validate Name Field
Name:
Validate
2. Include jQuery library from Google CDN
3. Write RegEx (Regular Expressions) that accepts only alphabets (not accepting any numeric number and special characters)
/^[A-Za-z]+$/
Validate name field using jQuery and RegEx
1. On Button Click
Validate Name Field
$(document).ready(function(){
$("#submitButton").click(function(){
if ($("#name").val().replace(/ /g,"").match(/^[A-Za-z]+$/)) {
alert("User Name is Correct");
}
else if($("#name").val() == ""){
alert("You can not leave this blank");
}
else{
alert("Please Enter Only Alphabets");
}
});
});
Name:
Validate
2. When Name Field Loses Focus
Move the cursor to another field or click anywhere on page:
Validate Name Field
$(document).ready(function(){
$("#name").blur(function(){
if ($(this).val().replace(/ /g,"").match(/^[A-Za-z]+$/)) {
$("#nameValidationMsg").text("User Name is Correct");
$("#nameValidationMsg").css("color", "green");
}
else if($("#name").val() == ""){
$("#nameValidationMsg").text("You can not leave this blank");
$("#nameValidationMsg").css("color", "red");
}
else{
$("#nameValidationMsg").text("Please Enter Only Alphabets");
$("#nameValidationMsg").css("color", "red");
}
});
});
Name:
Email:
Validate
3. On Key-Press
Just simply replace blur() method in previous example to keyup() method.
$("#name").keyup(function(){
//actions as in previous code
});
Validate using all three method click, blur & keyup in one code
Validate Name Field
$(document).ready(function(){
$("#name").on("blur keyup", function(){
if ($(this).val().replace(/ /g,"").match(/^[A-Za-z]+$/)) {
$("#nameValidationMsg").text("User Name is Correct");
$("#nameValidationMsg").css("color", "green");
}
else if($("#name").val() == ""){
$("#nameValidationMsg").text("You can not leave this blank");
$("#nameValidationMsg").css("color", "red");
}
else{
$("#nameValidationMsg").text("Please Enter Only Alphabets");
$("#nameValidationMsg").css("color", "red");
}
});
$("#submitButton").click(function(){
if ($("#name").val().replace(/ /g,"").match(/^[A-Za-z]+$/)) {
alert("User Name is Correct");
}
else if($("#name").val() == ""){
alert("You can not leave this blank");
}
else{
alert("Please Enter Only Alphabets");
}
});
});
Name:
Email:
Validate
If you have any question please feel free to ask in comments