【vue】vee-validate 表單驗證詳解
Pre:安裝
npm install [email protected]
內建的校驗規則
-
after{target} - 比target要大的一個合法日期,格式(DD/MM/YYYY)
-
alpha - 只包含英文字元
-
alpha_dash - 可以包含英文、數字、下劃線、破折號
-
alpha_num - 可以包含英文和數字
-
before:{target} - 和after相反
-
between:{min},{max} - 在min和max之間的數字
-
confirmed:{target} - 必須和target一樣
-
date_between:{min,max} - 日期在min和max之間
-
date_format:{format} - 合法的format格式化日期
-
decimal:{decimals?} - 數字,而且是decimals進位制
-
digits:{length} - 長度為length的數字
-
dimensions:{width},{height} - 符合寬高規定的圖片
-
email - 不解釋
-
ext:[extensions] - 字尾名
-
image - 圖片
-
in:[list] - 包含在陣列list內的值
-
ip - ipv4地址
-
max:{length} - 最大長度為length的字元
-
mimes:[list] - 檔案型別
-
min - max相反
-
mot_in - in相反
-
numeric - 只允許數字
-
regex:{pattern} - 值必須符合正則pattern
-
required - 不解釋
-
size:{kb} - 檔案大小不超過
-
url:{domain?} - (指定域名的)url
使用:
1.main.js新增
import Vue from 'vue'
import VeeValidate, {Validator} from 'vee-validate';
import zh from 'vee-validate/dist/locale/zh_CN';
Validator.addLocale(zh);
const config = {
locale: 'zh_CN'
};
Vue.use(VeeValidate,config);
2.一個例子:
<p>
<input v-validate="'required|email'" name="email" type="text" placeholder="Email">
<span v-show="errors.has('email')" >{{ errors.first('email') }}</span>
</p>
關於 提示:errors,它是一條json資料
{
"errors": [
{
"field": "email",
"msg": " email 必須是有效的郵箱.",
"rule": "email",
"scope": "__global__"
}
]
}
==>errors.has('email’)//當前email是否有錯誤
==>errors.first('email’)//獲取關於當前field的第一個錯誤資訊,msg
當然,還有其他獲取方式
collect('email') -- 獲取關於當前field的所有錯誤資訊(msg_list,如果有那麼多的話)
all() -- 當前表單所有錯誤(list)
any() -- 當前表單是否有任何錯誤(true/false)
3.自定義校驗規則
(1)新增自定義規則
//自定義規則——手機號碼判斷
const isMobile = {
messages: {
zh_CN:field => field + '必須是11位手機號碼',//field 就是自定義規則的名字
},
validate: (value, args) => {
return value.length == 11 && /^((13|14|15|17|18)[0-9]{1}\d{8})$/.test(value)
}
}
Validator.extend('mobile', isMobile);//相當於起了個別名
(2)更新規則提示資訊
const dictionary = {
zh_CN: {
messages: {
mobile: () => '這個手機號有毒'
},
attributes:{
mobile:'--修改預設為空欄位--'
}
}
};
Validator.updateDictionary(dictionary);
(3)為空時候的預設提示的修改
const dictionary = {
zh_CN: {
messages: {
mobile: () => '這個手機號有毒',
required:(field)=> "請輸入"+field
},
attributes:{
//mobile:'--修改預設為空欄位--'
}
}
};
Validator.updateDictionary(dictionary);
(4)使用
<div>
<input v-validate="'required|mobile'" name="mobile" type="text" placeholder="mobile">
<span v-show="errors.has('mobile')" >{{ errors.first('mobile') }}</span>
</div>