【问题标题】:Using the jQuery validate plugin to check if one or more checkboxes (with different names) are selected使用 jQuery 验证插件来检查是否选择了一个或多个复选框(具有不同的名称)
【发布时间】:2012-11-21 10:31:59
【问题描述】:

好的,所以我正在为 Drupal 7 站点实现 jQuery 验证插件。我遇到的问题是表单的一部分生成了多个名称略有不同的复选框。因此,似乎没有直接的方法可以使用验证器插件来检查是否至少选中了其中一​​个复选框。

http://docs.jquery.com/Plugins/Validation#API_Documentation

更具体地说,用户必须选择一个或多个主题类别。这些复选框的名称如下:“field_themes[und][52]”、“field_themes[und][55]”、“field_themes[und][64]”和“field_themes[und][65]”。

除此之外,我们还有一个与其他复选框无关的复选框,也必须选中。那是为了同意政策等。该插件很容易覆盖该插件,但我认为它会使其他 chekcboxes 的解决方案变得更加棘手。我还有另一组复选框,但它们都使用相同的名称(Drupal 有时很痛苦)。

所以我考虑了一下,认为也许我可以使用 submitHandler。所以我想出了下面...

$('#photo-node-form').validate({
  rules: {
    'field_first_name[und][0][value]': 'required',
    'field_last_name[und][0][value]': 'required',
    'field_email_address[und][0][email]': {
      required: true,
      email: true,
    },
    'field_product_type[und]': 'required',
    'field_terms_and_conditions[und]': 'required',
  },
  messages: {
    'field_first_name[und][0][value]': 'Please enter your first name.',
    'field_last_name[und][0][value]': 'Please enter your last name.',
    'field_email_address[und][0][email]': 'Please enter a valid email address.',
    'field_product_type[und]': 'Please select a product.',
    'field_terms_and_conditions[und]': 'You must confirm that you are 18 or older and agree to the terms and conditions.',
  },
  submitHandler: function(form) {
    //Verify that at least one theme category is selected.
    var themeCatSelected = false;

    //First we have to find all of theme
    $('#photo-node-form input:checkbox').each(function(i) {
      //Make sure this is a theme checkbox
      var name = $(this).name;
      var isTheme = false;
      stristr(name, 'field_themes[und]', isTheme);

      if (isTheme && this.checked) {
        //See if this is checked
        themeCatSelected = true;
      }
    });

    if (!themeCatSelected) {
      //Do something to alert the user that is not a popup alert
      return false; //Prevent form submittion
    }

    form.submit();
  }
});

//A JS reproduction of the PHP stristr function
function stristr (haystack, needle, bool) {
  var pos = 0;
  haystack += '';
  pos = haystack.toLowerCase().indexOf((needle + '').toLowerCase());

  if (pos == -1) {
    return false;
  }
  else {
    if (bool) {
      return haystack.substr(0, pos);
    }
    else {
      return haystack.slice(pos);
    }
  }
}

所以我遇到的问题是我不确定如何在正常区域中放置错误以显示此 submitHandler 函数的错误。我什至不确定这是否是最好的方法。有人有什么想法吗?

谢谢!

【问题讨论】:

    标签: php javascript jquery validation drupal


    【解决方案1】:

    你会想要做这些事情:

    1. 为您的复选框创建一个组
    2. 创建自定义验证方法以确保至少检查其中一个
    3. 为每个复选框的规则对象添加规则
    4. 自定义errorPlacement 函数以将您的错误放在适当的位置

    这是#2 的代码(请参阅here 了解选择器的工作原理):

    $.validator.addMethod("custom_checks", function(value, element) {
        return $('#photo-node-form input[name^="field_themes[und]"]:checked').length > 0;
    }, 'Please check one of these');
    

    这是#1 和#3 的一部分的代码:

    var tmpChecks = [], myRules = {
     'field_first_name[und][0][value]': 'required',
     'field_last_name[und][0][value]': 'required',
     'field_email_address[und][0][email]': {
      required: true,
      email: true,
     },
     'field_product_type[und]': 'required',
     'field_terms_and_conditions[und]': 'required'
    };
    $('#photo-node-form input[name^="field_themes[und]"]').each(function(){
       tmpChecks.push(this.name); //This is the start of #1
       myRules[$(this).attr("name")] = {
        custom_checks: true  
       }; //#3
    });
    

    对于 #4,将其添加到您的验证对象中:

    errorPlacement: function(error, element) {
        if (element.attr("name").match(/^field_themes\[und\]/)){
       $('#checkbox_errors').html(error);
        } else {
       error.insertAfter(element);
        }
    }
    

    你最终会像这样调用 validate:

    $("#photo-node-form").validate({
        rules: myRules,
        groups: {
            checks: tmpChecks.join(' ')   //the rest of #1
        },
        errorPlacement: function(error, element) {
            if (element.attr("name").match(/^field_themes\[und\]/)){
                //I added this span after all the textboxes, you can figure this out in a more dynamic way if you prefer               
               $('#checkbox_errors').html(error); 
            } else {
               error.insertAfter(element);
            }
        }
    });
    

    ​ 这是一个更简单形式的工作示例:http://jsfiddle.net/ryleyb/nUbGk/1/

    【讨论】:

    • 谢谢,今晚我会去试一试。太棒了!
    • 我看到它在您的示例中有效。但不幸的是,它似乎不想在我的环境中工作。我想知道是不是因为我的网站运行的是 jQuery 1.4.4。
    • 所以它没有调用 custom_checks 方法。仍在努力解决这个问题。
    • 什么不起作用?在调用验证并确认myRulestmpChecks 包含您期望的项目之前,我会在您的调试器中暂停。我认为它与 jQuery 1.4.4 无关 - 请参见此处:jsfiddle.net/ryleyb/nUbGk/2
    • 好的,所以我终于让它与你的方法一起工作了。问题是我们的设计师决定用 css 隐藏复选框(显示:无和可见性:隐藏)然后将标签变成按钮。问题是,由于没有显示它们,jQuery 只是跳过了它们。一旦我删除了那个 css,问题就消失了,它验证得很好。为了从那里隐藏它​​们,我将它们的父 div 设置为溢出:隐藏并将它们定位在页面之外。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-16
    • 2013-01-18
    • 2012-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多