How to mark required field in jQuery Validate
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开发者_StackOverflow.
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
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
This is possible
- Get all the inputs in form
- Iterate and find if the input has rule required
- If Yes, find the label of that input
- 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 *
}
});
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.
精彩评论