How to mark required field in jQuery Validate

6.3k views Asked by At

I'm using jQuery Validate and xVal to validate in input forms. This works great. However, I do want to mark my required fields with an asterix (*) or something like that to show which field is actually required.

I could do this by hand, but since I already generate my validation rules with xVal I thought I could mark the required fields automatically based on the provided rules.

Is there a way to hook into either xVal or jQuery Validate to retrieve the rules, or somehow make them mark my required fields?

I'm using the latest versions of jQuery and jQuery Validate.

Thanks

3

There are 3 answers

1
Sjoerd On

It is probably easiest to make a separate "rules" variable which you pass to both jQuery and some other function. This other function would loop through it and mark all required fields as such.

3
Starx On

Give the class required to the form elements, and use the following code

$(document).ready(function() {
     $('<span style="color:red;">*</span>').insertAfter('.required');
});

This will attach "*" to every elements with required class

Hope it helps

0
kiranvj On

This is possible

  1. Get all the inputs in form
  2. Iterate and find if the input has rule required
  3. If Yes, find the label of that input
  4. Append * at the end of the label text

Your code will look something like this

    $.each($("#you-form input"), function( index, element ) {
      var rule =  $(element).rules() ; // this will get the rules for each input
      if(rule && rule.required) {
        //find label and append red *
      }
    });