1

我正在尝试为自定义验证器添加新的错误消息。首先,我以这种方式更改了验证错误的默认语言:

import VeeValidate, { Validator } from 'vee-validate';
import it from 'vee-validate/dist/locale/it';


Validator.localize({ it: it });
Vue.use(VeeValidate, { inject: false, fastExit: false, locale: 'it' });

这是扩展验证器(在另一个文件中):

this.$validator.extend('dateFormat', {
                    validate: value => {
                        let reg = /(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)[0-9][0-9]/;
                    
                    if (reg.exec(value) === null) {
                        return false;
                    }
                    return true;
                }
            });
            validators.push('dateFormat');

当日期格式不正确时,如何显示自定义消息?谢谢

4

2 回答 2

1

两种方式:(根据VeeValidate3 文档

您可以通过在验证函数本身中返回字符串来更改错误消息:

import { extend } from 'vee-validate';

extend('positive', value => {
    if (value >= 0) {
        return true;
    }

    return 'This field must be a positive number';
});

或者,您可以使用扩展格式并传入一个message属性:

this.$validator.extend('dateFormat', {
    validate: value => {
        let reg = /(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)[0-9][0-9]/;
               
        if (reg.exec(value) === null) {
            return false;
        }
        return true;
    },
    // message property:
    message: 'The date format is incorrect',
});
validators.push('dateFormat');

本土化

如果您希望支持多种语言,上述解决方案将不够用。

根据文档,您应该能够使用{ localize }导入和以下对象语法为任何语言添加本地化消息:

import { localize } from 'vee-validate';

localize({
  en: {
    messages: {
      required: 'this field is required',
      min: 'this field must have no less than {length} characters',
      max: (_, { length }) => `this field must have no more than ${length} characters`
    }
  }
});

作为旁注,您还可以将if (reg.exec(value) === null) ...行简化为:

return reg.exec(value) !== null;
于 2020-07-23T22:24:25.360 回答
0

这就是我解决它的方法,不知道这是否是最佳做法,但似乎有效:

//Add this line
it.messages.dateFormat = function (field) { return 'Format for ' + field + ' not valid'; };
Validator.localize({ it: it });
Vue.use(VeeValidate, { inject: false, fastExit: false, locale: 'it' });
于 2020-07-24T13:41:54.973 回答