jQuery Validation: Add a Required Field Marker
1 min read
1 min read
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:$(".required").append("(*)");Alternatively, if (b) you have your jQuery validators as a set of rules, in the form
{..then you can iterate over those rules and process them directly:
rules: {
firstname: {
required: true,
rangelength: [2,5]
},
...
}
...
}
for(var propName in validationRules.rules){Here's a live demo: http://jsbin.com/ojuwuy/2/edit#javascript,live. Easy, huh?
if(validationRules.rules[propName].required !== undefined){
$("(*)").insertAfter($("*[name=" + propName + "]", $("form")));
}
}