詳解vue表單驗證組件 v-verify-plugin,vuev-verify-plugin
verify
github:https://github.com/liuyinglong/verify
npm:https://www.npmjs.com/package/vue-verify-plugin
install
npm install vue-verify-plugin
use
html
<div> <div> <input type="text" placeholder="姓名" v-verify.grow1="username" v-model="username"/> <label v-verified="verifyError.username"></label> </div> <div> <input type="password" placeholder="密碼" v-verify.grow1="pwd" v-model="pwd"/> <label v-verified="verifyError.pwd"></label> </div> <button v-on:click="submit">確認</button> </div>
js
import Vue from "vue";import verify from "vue-verify-plugin";Vue.use(verify);export default{ data:function(){ return { username:"", pwd:"" } }, methods:{ submit:function(){ if(this.$verify.check()){ //通過驗證 } } }, verify:{ username:[ "required", { test:function(val){ if(val.length<2){ return false; } return true; }, message:"姓名不得小於2位" } ], pwd:"required" }, computed:{ verifyError:function(){ return this.$verify.$errors; } }}
指令說明
v-verify
v-erify 在表單控制項元素上建立資料的驗證規則,他會自動匹配要驗證的值以及驗證的規則。
v-verify 修飾符說明
該指令最後一個修飾符為自訂分組
//自訂teacher分組v-verify.teacher//自訂student分組v-verify.student//驗證時可分開進行驗證 //驗證student 分組this.$verify.check("student")//驗證teacher 分組this.$verify.check("teacher")//驗證所有this.$verify.check();
v-verified
v-verified 錯誤展示,當有錯誤時會展示,沒有錯誤時會加上style:none,預設會展示該資料所有錯誤的第一條
該指令為文法糖(見樣本)
<input v-model="username" v-verify="username"><label v-show="$verify.$errors.username && $verify.$errors.username.length" v-text="$verify.$errors.username[0]"></label><!--等價於--><label v-verified="$verify.$errors.username"></label><!--展示所有錯誤--><label v-verified.join="$verify.$errors.username">
修飾符說明
.join 展示所有錯誤 用逗號隔開
自訂驗證規則
var myRules={ phone:{ test:/^1[34578]\d{9}$/, message:"電話號碼格式不正確" }, max6:{ test:function(val){ if(val.length>6) { return false } return true; }, message:"最大為6位" }}import Vue from "vue";import verify from "vue-verify-plugin";Vue.use(verify,{ rules:myRules});
以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援幫客之家。