JQuery验证多个字段,但有一个错误

时间:2009-08-17 16:44:10

标签: jquery jquery-validate

如何使用JQuery Validate插件为3个字段添加一条错误消息。例如3个dob字段。默认情况下,如果所有3个字段都留空,我将收到3条错误消息。我只想将一个错误链接到3个字段。如果有任何空白,则会出现错误。

7 个答案:

答案 0 :(得分:54)

与Chris的相似

$("form").validate({
    rules: {
        DayOfBirth: { required: true },
        MonthOfBirth: { required: true },
        YearOfBirth: { required: true }
    },
    groups: {
        DateofBirth: "DayOfBirth MonthOfBirth YearOfBirth"
    },
   errorPlacement: function(error, element) {
       if (element.attr("name") == "DayOfBirth" || element.attr("name") == "MonthOfBirth" || element.attr("name") == "YearOfBirth") 
        error.insertAfter("#YearOfBirth");
       else 
        error.insertAfter(element);
   }
});

答案 1 :(得分:13)

您可以使用groups选项将输入组合在一起。如果每个输入都有错误消息,则只显示一个。

您可能希望覆盖与每个字段关联的消息,因此它们会更有意义。例如,默认情况下,您可能会收到一条错误消息,例如“此字段是必需的”。好吧,当有三个输入时,这对用户来说并不好。您可能希望覆盖该消息,说“需要本地号码”。对于此示例,我只是通过“请输入有效的电话号码”覆盖所有错误消息。

<input type="text" name="countryCode" />
<input type="text" name="areaCode" />
<input type="text" name="localNumber" />

groups: {
  phoneNumber: "countryCode areaCode localNumber"
},
rules: {
  'countryCode': {
    required: true,
    minlength:3,
    maxlength:3,
    number:true
  },
  'contactInformation[areaCode]': {
    required: true,
    minlength:3,
    maxlength:3,
    number:true
  },
  'contactInformation[localNumber]': {
    required: true,
    minlength:4,
    maxlength:4,
    number:true
  },
},
messages: {
  "countryCode": {
    required: "Please enter a valid Phone Number",
    minlength: "Please enter a valid Phone Number",
    maxlength: "Please enter a valid Phone Number",
    number: "Please enter a valid Phone Number"
  },
  "areaCode": {
    required: "Please enter a valid Phone Number",
    minlength: "Please enter a valid Phone Number",
    maxlength: "Please enter a valid Phone Number",
    number: "Please enter a valid Phone Number"
  },
  "localNumber": {
    required: "Please enter a valid Phone Number",
    minlength: "Please enter a valid Phone Number",
    maxlength: "Please enter a valid Phone Number",
    number: "Please enter a valid Phone Number"
  }
},

答案 2 :(得分:4)

我以为我应该分享这个。完整的代码对我有用。

<强> HTML

<div class="clearfix bl">
    <label>Fecha de nacimiento</label>
    <select name="fechanacimdia" id="fechanacimdia"></select>
    <select name="fechanacimmes" id="fechanacimmes"></select>
    <select name="fechanacimano" id="fechanacimano"></select>
</div>

<强> JS

//hay que poblar selects de fecha
dia = $('#fechanacimdia');
mes = $('#fechanacimmes');
ano = $('#fechanacimano');
dia.append('<option>Día</option>');
for(i=1;i<=31;i++) {
    dia.append('<option value="'+i+'">'+i+'</option>');
}
meses = ["Enero","Febrero","Marzo","Abril","Mayo","Junio","Julio","Agosto","Septiembre","Octubre","Noviembre","Diciembre"]
mes.append('<option>Mes</option>');
for(i=1;i<=12;i++) {
    mes.append('<option value="'+i+'">'+meses[i-1]+'</option>');
}
d = new Date();
year = d.getFullYear();
maxage = 100;
minage = 16;
ano.append('<option>Año</option>');
for(i=year-minage;i>=year-maxage;i--) {
    ano.append('<option value="'+i+'">'+i+'</option>');
}


//--------- validate ------------------------

$('#formulario').validate({
    rules: {
        fechanacimdia: { required: true },
        fechanacimmes: { required: true },
        fechanacimano: { required: true, validdate: true }
    },
    groups: {
        fechanacim: "fechanacimdia fechanacimmes fechanacimano"
    },
    messages: {
        fechanacimdia: "Fecha de nacimiento no es válida.",
        fechanacimmes: "Fecha de nacimiento no es válida.",
        fechanacimano: "Fecha de nacimiento no es válida."
    },
});
//funcion auxiliar para validar fecha de nacimiento correcta
jQuery.validator.addMethod("validdate", function(value, element) {
    var month = +$('#fechanacimmes').val() - 1; // Convert to numbers with "+" prefix
    var day = +$('#fechanacimdia').val();
    var year = +$('#fechanacimano').val();
    var date = new Date(year, month, day); // Use the proper constructor
    return date.getFullYear() == year && date.getMonth() == month && date.getDate() == day;
});

答案 3 :(得分:3)

这适用于HTML部分:

<div>
    <p class="myLabel left">Date of birth:</p>
    <p class="mandatory left">*</p>
    <div class="left">
        <p><input type="text" name="dobDay" class="required" /></p>
        <p><i>dd</i></p>
    </div>
    <div class="left">
        <p><input type="text" name="dobMonth" class="required" /></p>
        <p><i>mm</i></p>
    </div>
    <div class="left">
        <p><input type="text" name="dobYear" class="required" /></p>
        <p><i>yyyy</i></p>
    </div>
    <div class="clear"></div>
    <div class="myError">
        <label for="dateOfBirth" class="error">Please enter a valid date.</label>
    </div>
</div>

这是我使用的脚本:

$(document).ready(function() {

$("#myForm").validate({
    groups: {
      dateOfBirth: "dobDay dobMonth dobYear"
    },
    rules: {
      'dobDay': {
        required: true,
        minlength:1,
        maxlength:2,
        range: [1, 31],
        number:true
      },
      'dobMonth': {
        required: true,
        minlength:1,
        maxlength:2,
        range: [1, 12],
        number:true
      },
      'dobYear': {
        required: true,
        minlength:4,
        maxlength:4,
        number:true
      },
    },
});
});

所有HTML部分都可以根据需要自定义。我使用了这些复杂的布局,因为我需要将此字段添加到已存在的表单中。但这是一个有效的例子! 希望它对任何人都有帮助!

答案 4 :(得分:2)

我对它的看法是更改jQuery validator以验证具有validateable属性的任何内容以及标准输入。您可以获得插件here

1.9.0修改版本

基本上你导入新的jquery验证器并执行以下操作:

<script>
$.validator.addMethod(
    "groupnotnull",
    function(value, element) {
        return $("input[type='text']:filled",element).length!=0;
    },
    function(regexp, element) {
      return "At least one input must be specified";
    }
);
</script>

<div validateable="true" name="groupValidated" groupnotnull="true">
    <input type="text" name="foo"/>
    <input type="text" name="blah"/>
</div>

jQuery validator所需的修改是使其.attr('name')而不是.name,因为.name仅适用于表单字段。并修改键向上处理程序等以绑定到validateable元素的子项。

这比群组更具动态性,因为它允许相互之间相互验证字段,而不仅仅是单个实体。

答案 5 :(得分:1)

如果任何必填字段为空,则此代码将显示一个常见错误。

<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>  
  <script>
$(document).ready(function(){
  $("#myform").validate({
    invalidHandler: function(form, validator) {
      var errors = validator.numberOfInvalids();
      if (errors) {
        var message ='You missed ' + errors + ' fields.';
        $("#messageBox").html(message);
        $("#messageBox").show();
      } else {
        $("#messageBox").hide();
      }
    },
    showErrors: function(errorMap, errorList) {

    },
    submitHandler: function() { alert("Submit!") }
 })
});  
</script>

</head>
<body>
  <script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js"></script>
<div id="messageBox"></div> 
<ul id="errorlist"></ul>
 <form id="myform" action="/loginurl" method="post"> 
   <label>DOB1</label> 
   <input name="dob1" class="required" /> 
   <label>DOB2</label> 
   <input name="dob2" class="required" /> 
   <label>DOB3</label> 
   <input name="dob3" class="required" />
   <br/>
   <input type="submit" value="Submit"/>
 </form>
</body>
</html>

答案 6 :(得分:0)

一些选项:查看errorContainer。您可以将所有错误发送到完全独立的<div>。或者您可以查看invalid块,只需要errorMessage.show()命令。