jQuery Validation with Color - POST using AJAX
by Roydon DSouza
HTML
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
<form id="commentForm" class="contact" novalidate="novalidate" name="myForm" action="" method="post">
<input type="text" id="Employee_Name" name="EmployeeName" required="required" />
<br>
<input type="text" id="Employee_Last_Name" name="EmployeeLastName" required="required" />
<br>
<input type="submit" id="submitButton" value="Test" />
</form>
CSS
.has-error {
border:1px dotted red;
background:red;
}
.has-success {
border:1px dotted green;
background:green;
color:#fff;
}
JavaScript
$("#submitButton").click(function (e) {
e.preventDefault();
//preventing default submit
if ($("#commentForm").validate().form()) {
alert('Fire AJAX Post here');
} else {
alert('Invalid Data');
//no AJAX fired
}
}); //submit click
$("#commentForm").validate({
ignore: "",
submitHandler: function (form) {
alert("form is fine you can procced");
},
highlight: function (element, errorClass, validClass) {
$(element).addClass("has-error");
$(element).removeClass("has-success");
},
unhighlight: function (element, errorClass, validClass) {
$(element).removeClass("has-error");
$(element).addClass("has-success");
},
errorPlacement: function (error, element) {
//this stops error messgae from printing
//remove this to print error message next to element
}
});
//custom error message - will work if you remove errorPlacement
$("#Employee_Name").rules("add", {
required: true,
messages: {
required: "My 1st custom error message"
}
});
$("#Employee_Last_Name").rules("add", {
required: true,
messages: {
required: "My 2nd custom error message"
}
});