Code for Simple jQuery form validation
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
label.error { float: none; color: red; padding-left: .5em; vertical-align: top; }
</style>
<script language="javascript" type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script language="javascript" type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.10.0/jquery.validate.min.js"></script>
<script>
$(function() {
$( "#mytestform" ).validate({
rules: {
aname: {
required: true,
minlength: 4,
maxlength: 20,
customvalidation: true
},
lastname: {
required: true,
minlength: 4,
maxlength: 20,
lettersonly: true
}
},
messages: {
aname: {
required: "Dude, enter a name",
minlength: $.format("Keep typing, at least {0} characters required!"),
maxlength: $.format("Whoa! Maximum {0} characters allowed!")
}
}
});
$.validator.addMethod("customvalidation",
function(value, element) {
return /^[A-Za-z\d=#$%@_ -]+$/.test(value);
},
"Sorry, no special characters allowed"
);
$.validator.addMethod("lettersonly",
function(value, element) {
return this.optional(element) || /^[a-z]+$/i.test(value);
},
"Letters only please"
);
$('.address').each(function() {
$(this).rules('add', {
required: true,
minlength: 5,
maxlength: 10,
messages: {
required: "Required input",
minlength: "Must be at least {0} characters",
maxlength: "Must be less than {0} characters"
}
});
});
});
</script>
</head>
<body>
<form id="mytestform" name="" method="get" action="">
Name:
<input name="aname" size="20" />
last Name:
<input name="lastname"/>
adress:
<input name="adress" class="address" />
<input class="submit" type="submit" value="Submit"/>
</form>
</body>
</html>
Demo: