I have been searching for a long time now on how to do the simplest jQuery validate. (To change border color and background) That’s it, Nothing more! no text or anything extra. I have seen many ways but the code is just too long.
Here’s example of a long code. I dont think its effective way if i had more then 10 fields to validate.
$(document).ready(function(){
//global vars
var form = $("#customform");
var name = $("#name");
var email = $("#email");
//On blur
name.blur(validateName);
email.blur(validateEmail);
//On key press
name.keyup(validateName);
//On Submitting
form.submit(function(){
if(validateName() & validateEmail())
return true
else
return false;
});
//validation functions
function validateEmail(){
//testing regular expression
var a = $("#email").val();
var filter = /^[a-zA-Z0-9]+[a-zA-Z0-9_.-]+[a-zA-Z0-9_-]+@[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{2,4}$/;
//if it's valid email
if(filter.test(a)){
email.removeClass("error");
return true;
}
//if it's NOT valid
else{
email.addClass("error");
return false;
}
}
function validateName(){
//if it's NOT valid
if(name.val().length < 4){
name.addClass("error");
return false;
}
//if it's valid
else{
name.removeClass("error");
return true;
}
}
});
It smells as if you need some refactoring and extract the code that gets repeated all the time into its own function:
Use it like this (I also recommend turning your variables into parameters so
that you can use the validators on different fields):