jQuery验证:复选框的初始/即时验证 [英] jQuery validation: Initial/On the fly validation of checkbox

查看:116
本文介绍了jQuery验证:复选框的初始/即时验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用jquery验证插件: jQuery验证.现在,我有一个带有简单验证方法的代码段,该方法用于根据给定参数验证选中的复选框的数量

I am using the jquery validation plugin: jQuery validation. Now, I have this snippet with a simple validation method which is used to verify the number of checked checkboxes based on a given parameter

$.validator.methods.cbMinRequired = function (value, element, param) {
  return $(element).parent().find(":checked").length >= param;
};

$(function () {
    // validate the comment form when it is submitted
    $("#myform").validate({
        keyup: true,
        keypress: true,
        click: true,
        change: true,
        debug: true,
        errorClass: "invalid",
        rules: {
            mycheckboxes: {
                cbMinRequired: 1
            }
        }
    });
  });

查看我的小提琴: jsFiddle复选框验证示例

如您所见,我有问题.

我必须先触发提交"来验证表格.但我想在加载后对其进行验证.按照我的想法,最初没有选择触发提交的选项,因为最后我想使用此按钮触发保存操作",该操作不应在页面加载后调用.

I have to validate the form by triggering "submit" first. But I want to validate it after load. There is no option to trigger the submit initially as I think, since at the end I want to trigger a 'save action' with this button which shouldn't be invoked after page load.

有什么想法可以解决这个问题吗?

Any kind of ideas how to cope with this?

推荐答案

您的代码:

$(function () {
    $("#myform").validate({
        keyup: true,
        keypress: true,
        click: true,
        change: true,
        debug: true,
        errorClass: "invalid",
        rules: {
            mycheckboxes: {
                cbMinRequired: 1
            }
        }
    });
});

您的代码存在一个主要问题: 此插件没有这样的选项 keyupkeypressclickchange..它们分别称为onkeyuponfocusoutonclickonsubmit,默认情况下已为"true". ..在不破坏插件的情况下不能将它们设置为true.您只能将它们设置为false以禁用,或将它们设置为自定义功能.

There is a major issue with your code: There are no such options for this plugin called keyup, keypress, click, or change. They are called onkeyup, onfocusout, onclick, and onsubmit and they are already "true" by default... they cannot be set to true without breaking the plugin. You can only set them to false to disable, or set them to a custom function.

然后,您可以使用 .valid()方法,以编程方式随时触发验证测试.

Then you can programatically trigger a validation test at any time you wish by using the .valid() method.

$("#myform").valid();

这将触发页面加载的验证...

This will trigger validation on page load...

$(function () {

    $("#myform").validate({ // initialize the plugin
        // options
    });

    $("#myform").valid(); // trigger validation on page load

});

您的演示版已更新: http://jsfiddle.net/sVwFb/4/

这篇关于jQuery验证:复选框的初始/即时验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆