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

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


当前回答

添加自定义或字段标签或任何与正在验证的字段相关的动态标签。 你可以通过dom选择任何东西,并将其添加到任何带有错误消息的地方。

下面是一个在required消息开头添加字段标签而不是“this field”的例子。

jQuery.extend(jQuery.validator.messages, {

    required: function(result,e){

        let field_label = "This field ";

        if($(e).closest('.form-group').find('label').length > 0)
            field_label = $(e).closest('.form-group').find('label').html();

        return field_label+" is required.";

        },

});

其他回答

这招对我很管用:

// 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.",
            }
        }
    })

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

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}.")
});

另一种可能的解决方案是遍历字段,向每个字段添加相同的错误消息。

$('.required').each(function(index) {
  $(this).rules("add", {
    messages: {
      required: "Custom error message."
   }
  });
});

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

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

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

添加自定义或字段标签或任何与正在验证的字段相关的动态标签。 你可以通过dom选择任何东西,并将其添加到任何带有错误消息的地方。

下面是一个在required消息开头添加字段标签而不是“this field”的例子。

jQuery.extend(jQuery.validator.messages, {

    required: function(result,e){

        let field_label = "This field ";

        if($(e).closest('.form-group').find('label').length > 0)
            field_label = $(e).closest('.form-group').find('label').html();

        return field_label+" is required.";

        },

});