-1

I am trying to use jQuery Validate plugin addMethod for validating multiple fields of similar validation conditions. Those fields are required depending on another dropdown selection. How can I use required:true property inside an addMethod?

All I can think of is JS code to check if the field is empty. But I want a cleaner way.

Here's the code:

HTML:

<td>
<input type="text" name="examname1" id="en1" maxlength="8" size="8" disabled="disabled" onkeypress="return isAlphaKey(event)" />
</td>

jQuery :

//common validation method for education details in first row
jQuery.validator.addMethod ("prox_education1", function (value, element) {
        if ($("#education").val() >= 1)
        {
            ?????
        }
}, "This field is required");

How do I make the field required if the condition is true?

jQuery.validator.addMethod (...) {
if (condition)
{
   make this element required
}
else
{
   ignore
}
"Error: This field is required and you left it blank"
user1543784
  • 271
  • 2
  • 4
  • 19
  • please share your code and explain what you need – Arun P Johny Sep 03 '14 at 05:50
  • inside the plugin's addMethod you can use `this.optional(element)` to check whether an element is required or not – Arun P Johny Sep 03 '14 at 05:50
  • I don't want to check if the element is required. I want to make it required if the condition is true. – user1543784 Sep 03 '14 at 06:11
  • Sounds like the following may be of use: http://stackoverflow.com/questions/3033910/jquery-how-to-dynamically-add-a-validation-rule – Pebbl Sep 03 '14 at 06:20
  • The example you gave uses id for adding rules. I want to add the rules for multiple fields. Please see the code and suggest what can be used in place of ????. – user1543784 Sep 03 '14 at 06:30
  • I could make the field required by using `$(element).rules ("add", { required: true, });` But now the error is not going away even when the field is not blank. – user1543784 Sep 03 '14 at 06:58

1 Answers1

1

If you want to make a field required based on a condition, you can pass a function as the required rule value and it can return true/false like

rules: {
    somefield: {
        required: function () {
            return $('#f1').is(':checked');
        }
    }
},

Demo: Fiddle


Another option is to use the rules api like

//add
$('#f2').rules('add', {
    required: true
});
//remove
$('#f2').rules('remove', 'required');

Demo: Fiddle

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
  • This will work for one field. But I want to make **multiple** fields required based on the **same** condition. That's why I'm using addMethod. I hope I'm explaining it correctly. – user1543784 Sep 03 '14 at 07:08
  • 1
    @user1543784 then create a demo using the attached fiddles to demonstrate your problem – Arun P Johny Sep 03 '14 at 07:14