One validation message for multiple fields

2019-09-14 07:03发布

问题:

I'm having a problem with jQuery validation and could use some suggestions.

Is there a way I can validate the three Phone Number fields in this form while only having one error message for the group? Any help is greatly appreciated.

Form

<form id="mForm" name="form">
<div class="field right">
  <label class="labelStd" id="phoneNumber">Phone Number*</label>
  <input name="txtPhone1" type="text" maxlength="3" id="txtPhone1" class="small-phone" name="txtPhone1" Onchange="Tab(this, 'txtPhone2');" />
  <input name="txtPhone2" type="text" maxlength="3" id="txtPhone2" class="small-phone" name="txtPhone2" Onchange="Tab(this, 'txtPhone3');" />
  <input name="txtPhone3" type="text" maxlength="4" id="txtPhone3" class="small-phone" name="txtPhone3" />
</div>

<button type="submit" id="btn_submit" class="button-black right">SEND</button>
</form>

Script (with jquery validate)

<script type="text/javascript">
$("#mForm").validate({

onfocusout:false,
focuseInvalid:false,
onkeyup:false,

rules: {

    txtPhone1:{
            required: true,
            digits: true,
            minlength: 3,
            maxlength: 3
        },
    txtPhone2:{
            required: true,
            digits: true,
            minlength: 3,
            maxlength: 3
        },
    txtPhone3:{
            required: true,
            digits: true,
            minlength: 4,
            maxlength: 4
        }
    },

messages: {

    txtPhone1: "Your phone number is required.",
    txtPhone2: "Your phone number is required.",
    txtPhone3: "Your phone number is required."
}


  });

  $("#mForm").submit(function(){

if($(this).valid()){

form.submit();

}

else{ }

 });
</script>

回答1:

You need to use the groups option...

Specify grouping of error messages. A group consists of an arbitrary group name as the key and a space separated list of element names as the value. Use errorPlacement to control where the group message is placed.

groups:  {
    someArbitraryName: "txtPhone1 txtPhone2 txtPhone3"
}

Generic Demo: http://jsfiddle.net/3RFsa/

Sidenote:

Regarding your submit handler...

$("#mForm").submit(function(){
    if($(this).valid()){
        form.submit();
    }
...

It's totally superfluous and unnecessary, so I would remove it entirely. By default, the plugin will automatically submit the form only if/when it's valid. If you'd like to do something else in addition to the submit(), you can use the plugin's submitHandler callback function. If you need to do something when the form fails validation, use the plugin's invalidHandler callback function.