4

I've been reviewing the list of options available for the jquery form validation plugin (http://docs.jquery.com/Plugins/Validation/validate#toptions). I'm tying to understand how the option groups work. The only code available in the official (?) website is:

// Use a table layout for the form, placing error messages in the next cell after the input.
$("#myform").validate({
  groups: {
    username: "fname lname"
  },
  errorPlacement: function(error, element) {
     if (element.attr("name") == "fname" 
                 || element.attr("name") == "lname" )
       error.insertAfter("#lastname");
     else
       error.insertAfter(element);
   },
   debug:true
 })

I understand that they are creating a group called "username" that groups two elements in a form: "fname" and "lname", but how is that groupd used? Actually, the first question I have is: what are the groups for? I thought it was to instruct the plugin to handle the elements in a group as a single unit and to also display a single error in case any of the elements trigger one (for example, if the two textboxes are marked as required, using the rules element, and if a value is missing in any of the two or the two of them then a single error label is displayed instead of two if the two elements have errors), but I've been trying with several examples and have not been able to get it work in this way. So, what are they for? how should I use them?

4

1 回答 1

7

groups选项所做的总和是只为组内的所有事物报告一条错误消息。在给定的示例中,如果您没有对fnameandlname和 both 进行分组,那么您将收到两条错误消息。与组,你只得到一个。该组的两个元素仍然是必需的。

听起来您正确理解了这一点,但是很难说出为什么您没有使该示例起作用。使用此 HTML:

<form id="myform">
  First Name: <input type="text" name="fname" id="fname"/><br>
  Last Name: <input type="text" name="lname" id="lname"/><br>

    <input type="submit"/>
</form>​

这个验证代码:

$("#myform").validate({
    rules: {
        fname: { required: true },
        lname: { required: true }
    },
  groups: {
    username: "fname lname"
  },
  errorPlacement: function(error, element) {
     if (element.attr("name") == "fname" 
                 || element.attr("name") == "lname" )
       error.insertAfter("#lname");
     else
       error.insertAfter(element);
   }
 })​

在我看来没问题:http: //jsfiddle.net/ryleyb/cbJj6/

我帮助某人的一个更复杂的例子是:使用 jQuery 验证插件来检查是否选择了一个或多个复选框(具有不同的名称)
最终,该问题的组部分要求一组复选框中的一个复选框是检查,如果不是,则只需要一条消息。

于 2013-01-03T21:01:03.637 回答