1

I need to validate the floor fields that mention below.

<form id="test_form" >
<input name="floor[abc]" type="text" class="input_txt_l " value="" />
<input name="floor[cde]" type="text" class="input_txt_l " value="" />
</form>

I tried with jquery validator plug-in.

jQuery("#test_form").validate({
    rules: {
    'floor[]':{
        required:true
    }},
messages: {
        'floor[]':{
            required:"floor is required."
            }
     }
    });

In here validation is not working. but if the floor has no index , It works well. If someone have idea to fix this issue please help me.

KTAnj
  • 1,346
  • 14
  • 36

1 Answers1

4

There are different ways to solve your problem:

Either you use addClassRules:

// using the class name instead of field name
jQuery.validator.addClassRules("input_txt_l", {
    required: true       
});

Or you handle each field separately, because in fact they are named different:

jQuery("#test_form").validate({
    rules: {
        'floor[abc]':{
            required:true
        },
        'floor[cde]':{
            required:true
        },
    }
});

Or you rename your fields:

HTML:

<input name="floor[][abc]" type="text" class="input_txt_l " value="" />
<input name="floor[][cde]" type="text" class="input_txt_l " value="" />

JavaScript:

jQuery("#test_form").validate({
    rules: {
    'floor[]':{
        required:true
    }},
});

fiddle is here.

axel.michel
  • 5,764
  • 1
  • 15
  • 25
  • what if only one is mandatory ?? – Bugfixer Aug 10 '16 at 05:13
  • @Bugfixer I am not sure if I get your question correctly, but in case you have just one exception you could go for something like floor[]:{required:false} and the specific field floor['fieldname']:{required:true} – axel.michel Aug 11 '16 at 10:44
  • I tried this and still not working. But then I figured out that I missed the quote for input field names and it works now. Thanks for this – Abaij Feb 11 '18 at 23:16