Javascript Jquery验证插件-仅在某些情况下用于数字字段

Javascript Jquery验证插件-仅在某些情况下用于数字字段,javascript,jquery,jquery-plugins,jquery-validate,Javascript,Jquery,Jquery Plugins,Jquery Validate,我试图使用jqueryvalidate对数值进行验证,但仅当选中单选按钮时;如果未选中单选按钮,则需要该字段,但用户可以插入字母数字值;问题在于,仅验证字段是否为空,并且console.log显示我想要的值(true或false),但在将数据发送到服务器时提交。这就是我所拥有的: $("#new_redeem_coupon").validate({ rules:{ 'redeem_coupon[confirmation_number]': { re

我试图使用jqueryvalidate对数值进行验证,但仅当选中单选按钮时;如果未选中单选按钮,则需要该字段,但用户可以插入字母数字值;问题在于,仅验证字段是否为空,并且console.log显示我想要的值(true或false),但在将数据发送到服务器时提交。这就是我所拥有的:

$("#new_redeem_coupon").validate({
    rules:{
        'redeem_coupon[confirmation_number]': {
            required: function(element){
                var v = $("#redeem_coupon_confirmation_number").attr("value");
                if($("#redeem_coupon_coupon_kind_0").attr("checked") == "checked"){
                    ret = (v == "");
                    console.log("VALUE1: " + ret);
                    return ret;
                }
                else{
                    var ret = (v == "" || isNaN(v));
                    console.log("VALUE2: " + ret);
                    return ret;
                }
            }
        }
    },
    errorPlacement:function(error, element){
        $(element).attr("title",error.html()).tooltip({track:true});
    },
    success:function(label){
    },
    errorClass: "invalid",
    focusCleanUp: true
});
我也尝试过以下代码,但没有成功;该值始终保持为false:

'redeem_coupon[confirmation_number]': { required:true, number: $("#redeem_coupon_coupon_kind_0").attr("checked") != "checked" }
提前感谢你的帮助


Pablo Martí

解决方案:使用下列
添加
删除
方法:

规则:

$("#new_redeem_coupon").validate({
    rules:{
        'redeem_coupon[confirmation_number]': {required: true}
    },
    errorPlacement:function(error, element){
        $(element).attr("title",error.html()).tooltip({track:true});
    },
    success:function(label){
    },
    errorClass: "invalid",
    focusCleanUp: true
});
我通过无线电添加了一个事件,以添加和删除每种情况的规则:

$(".coupon_kind_opt").change(function(){
    if($("#redeem_coupon_coupon_kind_0").attr("checked") == "checked"){
        $("#redeem_coupon_confirmation_number").rules("remove", "number");
    }
    else{
        $("#redeem_coupon_confirmation_number").rules("add", {
            number: true
        });
    }
})