I made a validation library for general JavaScript purposes only. It is even being tested! You can override whatever you want quite easily: https://github.com/parris/iz
As for highlighting invalid fields, you can simply change the style of that field or add a class. The example below only changes the background color of the input and adds a message.
Working example: http://jsfiddle.net/soparrissays/4BrNu/1/
$(function() { var message = $("#message"), field = $("#field"); $("#the-form").submit(function(event) { if (iz(field.val()).alphaNumeric().not().email().valid){ message.text("Yay! AlphaNumeric and not an email address"); field.attr("style","background:green;"); } else { message.text("OH no :(, it must be alphanumeric and not an email address"); field.attr("style","background:red;"); } return false; }); });
The validator is called iz. It just lets you combine the checks together, and it will tell you if everything went well, or if you check the “errors” object, it will give you more information. In addition, you can specify your own error messages. Check out the docs on github.
What happens here, we set the click handler for the submit event as soon as the page is ready. return false; at the bottom of the submit callback prevents the form from submitting. If you return true; , the form will continue. Instead of return false, you can also event.preventDefault(); but I prefer the return syntax for consistency. In the real world with several form elements, you can do something like this (psuedo code):
var passed = true; if (check field 1 is false) ... if (check field 2 is false) ... if (check field n is false) passed = false style and add message if passed return true else return false
The if statement checks the validation rules and makes changes to the DOM accordingly. Thus, you can provide a complete list of all passed and failed fields with a full description of what is wrong.
source share