How to mark required fields with jQuery Validate
Today I was tasked with marking all the required field in an ASP.NET MVC application with asterisks, next to the relevant labels. Initially it seemed that there would be no other solution than to go through every view and add it by hand. Fortunately, I realized that there was a far better solution, one that would only require 13 lines of code. We use the jQuery Validation plugin for client-side validation and this is configured with a number of validation rules. I realized that if I could hook into these rules, I had all the information that I needed.
The concept behind this solution is simple, really. You just need to intercept the initializing logic that sets up the validation rules and update the labels as needed. The code in its entirety can be seen below.
- var validateMethod = $.fn.validate;
- $.fn.validate = function (o) {
- if (o && o.rules) {
- for (var name in o.rules) {
- var rule = o.rules[name];
- if (rule.required === true) {
- var label = $('label[for=' + name + ']');
- label.text(label.text() + "*");
- }
- }
- }
- return $.proxy(validateMethod, this)(o);
- };
The code assigns the original validation method to a variable, saving it for later, while we assign the plugin a new method. This method contains our logic, ending up executing the original method. Notice that we must use the jQuery proxy function for assigning the target element to the this property inside the validation function as it expects. That's all there is to it. Of course, you can check for other types of validation rules and annotate the form fields accordingly if you need to. Just execute this code at any time before initializing your validation rules.
Comments