[js]vee-validate自定义告警信息和自定义规则

tech2025-07-26  10

https://vee-validate.logaretm.com/v2/guide/rules.html#date-format-params

本身框架自带很多验证,但是如果想自定义规则或者国际化,就需要一些自定义操作

1. 在页面的组件引用:

2. 在vue的computed里添加规则:

注意,有些规则不需要写promise回调,有些不写的话会报错:

Cannot read property 'then' of undefined

换成上面promise的写法即可

例如decimal这类正则验证可以不写:

https://stackoverflow.com/questions/59156440/how-to-validate-decimal-value-in-vee-validate-3-0-version

this.$validator.extend("decimal", { validate: (value, { decimals = '*', separator = '.' } = {}) => { if (value === null || value === undefined || value === '') { return { valid: false }; } if (Number(decimals) === 0) { return { valid: /^-?\d*$/.test(value), }; } const regexPart = decimals === '*' ? '+' : `{1,${decimals}}`; const regex = new RegExp(`^[-+]?\\d*(\\${separator}\\d${regexPart})?([eE]{1}[-]?\\d+)?$`); return { valid: regex.test(value), }; }, });

 

2. 国际化

实际对应的是

this.$validator.extend("decimal", {

decimal 关键字

现在页面引入

<script src="{{ asset('js/components/error_msg.js') ."?". config('cache.asset_postfix') }}"></script>

这是laravel的写法,需要留意的是,有时候会被打包产生缓存,更新不了js,这时候需要把 ."?". config('cache.asset_postfix')去掉

error_msg.js:

不是所有国际化都需要在Vue的类里面定义,如果本身框架自带的,只是想改变msg,就只需要在error_msg.js里面定义

加上配置:

注意对应名称

 

补充:

控制验证

resolve来返回结果

例子:

//用promise封装ajax请求 function ajaxPromise(type,_url){ return new Promise(function(resolve,reject){// Promis实例化 var xhr = new XMLHttpRequest(); xhr.open(type,_url); xhr.send(); xhr.addEventListener("readystatechange",function(){ if(xhr.readyState !=4 ){// 监听状态不对的时候 不指定函数 return; } if(xhr.readyState==4&&xhr.status==200){ var res = JSON.parse(xhr.responseText); console.log("ajaxPromise",res) resolve(res); // 回调成功返回 }else{ reject();// 回调失败返回 } }) }) }

 

 

最新回复(0)