我们可以在formitem上指定验证规则,有时候我们需要校验用户数据的值是否有效,这时候就需要用到自定义的validator
<el-form ref="form" :model="form" :rules="rules" label-width="260px">
rule的写法如下,这里分别加了必填验证,数字格式验证(使用的正则表达式),自定义校验:
rules: { ClientNumber: [ { required: true, message: 'The client number cannot be empty', trigger: 'blur', }, { type: 'string', pattern: /^[A-Za-z0-9]{1,25}$/, message: 'Client number should be a number or letter with maximum length of 25.', trigger: 'blur', }, { validator: ClientNumberValidator, trigger: 'blur', }, ], },
自定义方法的写法:
export default { ... data() { var ClientNumberValidator = async (rule, value, callback) => { const { code, data } = await checkClientNumberExists({ param1: value1, param2: value2, }) if (code && code === 200 && data == true) { callback( new Error( 'The Number has already been used .' ) ) } } return { ...