有一个简单的方法来改变默认的错误值在jQuery验证插件?

我只是想重写错误消息,以使我的应用程序更加个性化——我有很多字段,所以我不想为字段x单独设置消息……我知道我能做到!


当前回答

这招对我很管用:

// Change default JQuery validation Messages.
$("#addnewcadidateform").validate({
        rules: {
            firstname: "required",
            lastname: "required",
            email: "required email",
        },
        messages: {
            firstname: "Enter your First Name",
            lastname: "Enter your Last Name",
            email: {
                required: "Enter your Email",
                email: "Please enter a valid email address.",
            }
        }
    })

其他回答

我们可以指定文本字段的类型来代替这些自定义错误消息。

示例:设置字段类型为type = 'email'

然后插件将识别字段并正确验证。

@Josh:你可以从你的资源包中翻译消息来扩展你的解决方案

<script type="text/javascript">
    $.validator.messages.number = '@Html.Raw(@Resources.General.ErrorMessageNotANumber)';
</script>

如果你把这段代码放到你的_Layout中。cshtml (MVC),它可用于所有视图

将此代码添加到验证插件后包含的单独文件/脚本中,以覆盖消息,随意编辑:)

jQuery.extend(jQuery.validator.messages, {
    required: "This field is required.",
    remote: "Please fix this field.",
    email: "Please enter a valid email address.",
    url: "Please enter a valid URL.",
    date: "Please enter a valid date.",
    dateISO: "Please enter a valid date (ISO).",
    number: "Please enter a valid number.",
    digits: "Please enter only digits.",
    creditcard: "Please enter a valid credit card number.",
    equalTo: "Please enter the same value again.",
    accept: "Please enter a value with a valid extension.",
    maxlength: jQuery.validator.format("Please enter no more than {0} characters."),
    minlength: jQuery.validator.format("Please enter at least {0} characters."),
    rangelength: jQuery.validator.format("Please enter a value between {0} and {1} characters long."),
    range: jQuery.validator.format("Please enter a value between {0} and {1}."),
    max: jQuery.validator.format("Please enter a value less than or equal to {0}."),
    min: jQuery.validator.format("Please enter a value greater than or equal to {0}.")
});

这招对我很管用:

// Change default JQuery validation Messages.
$("#addnewcadidateform").validate({
        rules: {
            firstname: "required",
            lastname: "required",
            email: "required email",
        },
        messages: {
            firstname: "Enter your First Name",
            lastname: "Enter your Last Name",
            email: {
                required: "Enter your Email",
                email: "Please enter a valid email address.",
            }
        }
    })

而不是改变插件源代码,你可以包括一个额外的js文件,格式类似于下载本地化文件夹中的那些,并在加载validation.js后包括那个文件

jQuery.extend(jQuery.validator.messages, {
    required: ...,
    maxlength: jQuery.validator.format(...),
    ...
});