jQuery验证自定义消息,用于不同元素的动态变化 [英] Jquery validation custom message for different elements changing dynamically

查看:57
本文介绍了jQuery验证自定义消息,用于不同元素的动态变化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有维度字段的表单,并且按如下所示验证了表单.

I have a form with dimension fields and I validate the form as follows.

$("#myForm").validate({
        rules:{
            "length" : {
                required: true,
                number: true,
                range: [0, 101.1]
            },
            "width" : {
                required: true,
                number: true,
                range: [0, 101.1]
            },
            "weight" : {
                required: true,
                number: true,
                range: [0, 99.999]
            }
        },
        messages : {
            "length" : {
                required: globalCtx.requiredMsg,
                range: $("#selectedUnit").val() =="true" ? globalCtx.invalidSizeMetric : globalCtx.invalidSizeImperial
            },
            "width" : {
                required: globalCtx.requiredMsg,
                range: $("#selectedUnit").val() =="true" ? globalCtx.invalidSizeMetric : globalCtx.invalidSizeImperial 
            },
            "weight" : {
                required: globalCtx.requiredMsg,
                range: $("#selectedUnit").val() =="true" ? globalCtx.invalidWeightMetric : globalCtx.invalidWeightImperial
            }
        }
    });

每次更改单位时,我都会调用以下函数来更改错误消息以反映英制消息.

Every time the units is changed i call the function below to change the error message to reflect imperial messages.

function changeMetric(){
if($("#selectedUnit").val() =="true"){
        jQuery.extend(jQuery.validator.messages, {
            "weight":{
                range: globalCtx.invalidWeightMetric
            },
            "length" : {
                    range: globalCtx.invalidSizeMetric
                },
            "width" : {
                    range: globalCtx.invalidSizeMetric
                }
        });
    }else{
        jQuery.extend(jQuery.validator.messages, {
            "weight":{
                range: globalCtx.invalidWeightImperial
            },
            "length" : {
                range: globalCtx.invalidSizeImperial
            },
            "width" : {
                range: globalCtx.invalidSizeImperial
            }
        });
    }
}

但是此功能不会更新错误消息.

But this function is not updating the error message.

推荐答案

您将需要从函数中返回变量,否则将不会对其进行动态求值...

You'll need to return the variables from within a function or they will not be evaluated dynamically...

messages: {
    length: {
        required: function(element) {
            return globalCtx.requiredMsg;
        },
        range: function(element) {
            return $("#selectedUnit").val() =="true" ? globalCtx.invalidSizeMetric : globalCtx.invalidSizeImperial;
        }
    }, .... 

这篇关于jQuery验证自定义消息,用于不同元素的动态变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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