jQuery Validation: Add a Required Field Marker

When you use jQuery for validating input fields you might want to automatically (based on the validators) decorate your according field labels or input fields with appropriate markers that indicate required fields. This is common practice in web UIs and quite handy and intuitive for the user. Obviously you'd like this to happen on an automated basis rather than manually adding those markers which is more error prone. Using jQuery this is quite simple actually.

The idea is to do this process of adding markers after the validation has been hooked on your form. There are basically two possibilities:
(a) if you added your jQuery validators by directly annotating your input fields, then you might use a jQuery selector to find all those fields and append the marker appropriately (assume all your required fields have a class "required"):
Alternatively, if (b) you have your jQuery validators as a set of rules, in the form
rules: {
firstname: {
required: true,
rangelength: [2,5]
..then you can iterate over those rules and process them directly:
for(var propName in validationRules.rules){
if(validationRules.rules[propName].required !== undefined){
$("(*)").insertAfter($("*[name=" + propName + "]", $("form")));
Here's a live demo: http://jsbin.com/ojuwuy/2/edit#javascript,live. Easy, huh?



Your ad here?