首頁 > web前端 > Vue.js > 主體

詳解vue驗證器(vue-validator)的使用

青灯夜游
發布: 2020-11-05 17:57:09
轉載
4925 人瀏覽過

詳解vue驗證器(vue-validator)的使用

官方文件:http://vuejs.github.io/vue-validator/zh-cn/index.html

github專案網址:https:// github.com/vuejs/vue-validator

單獨使用vue-validator的方法見官方文檔,本文結合vue-router使用。

安裝驗證器

不加入自訂驗證器或無需全域使用的公用驗證器,在main.js中安裝驗證器,使用CommonJS 模組規格, 需要明確的使用 Vue.use() 安裝驗證器元件。

import Validator from 'vue-validator'
Vue.use(Validator)
登入後複製

與 vue-router 同時使用,必須在呼叫 router#map, router#start 等實例方法前安裝驗證。 

若要自訂驗證器,請建立一個js文件,在該文件中安裝驗證器元件。例如:validation.js

import Vue from 'vue'
import Validator from 'vue-validator'
Vue.use(Validator)
//自定义验证器
登入後複製

自訂驗證器

官方提供的api如下

input[type="text"]
input[type="radio"]
input[type="checkbox"]
input[type="number"]
input[type="password"]
input[type="email"]
input[type="tel"]
input[type="url"]
select
textarea
登入後複製

但是以上的不一定要滿足我們的需求,這時就需要用到另一個全域api,用來註冊和取得全域驗證器。

Vue.validator( id, [definition] )
登入後複製

範例  定義validation.js  內容如下

import Vue from 'vue'
import Validator from 'vue-validator'
Vue.use(Validator)
//自定义验证器
//添加一个简单的手机号验证 
//匹配0-9之间的数字,并且长度是11位
Vue.validator('tel', function (val) {
  return /^[0-9]{11}$/.test(val)
});
//添加一个密码验证
//匹配6-20位的任何字类字符,包括下划线。与“[A-Za-z0-9_]”等效。
Vue.validator('passw', function (val) {
  return /^(\w){6,20}$/.test(val)
});
登入後複製

使用驗證器

驗證器語法

<validator name="validation">
  <input type="text" v-model=&#39;comment&#39; id=&#39;comment&#39;
  v-validate:comment="{ minlength: 3, maxlength: 15 }">
    <div>
   <span v-show="$validation.comment.minlength">不得少于3个字符</span>
   <span v-show="$validation.comment.maxlength">不得大于15个字符</span>
    </div>
 </validator>
登入後複製

預設情況下, vue-validator 會依照 validator 和 v-validate 指令自動進行驗證。然而有時我們需要關閉自動驗證,在有需要時手動觸發驗證。如果你不需要自動驗證,可以透過 initial 屬性或 v-validate 驗證規則來關閉自動驗證。

如下:

<validator name="validation">
  <input type="text" v-model=&#39;comment&#39; id=&#39;comment&#39; 
  v-validate:comment="{ minlength: 3, maxlength: 15 }"  
  detect-change="off" initial=&#39;off&#39;>
  <div>
 <span v-show="$validation.comment.minlength">不得少于3个字符</span>
 <span v-show="$validation.comment.maxlength">不得大于15个字符</span>
     </div>
</validator>
登入後複製

Terminal 指令問題

<validator name="test_validator">
  <!-- @invalid:valid的逆 ,表示验证不通过 -->
  <input  @invalid="passwInvalid" @valid="passwok" 
  type="password" v-model=&#39;passw&#39; id=&#39;passw&#39; v-validate:passw="[&#39;passw&#39;]"  
  detect-change="off" initial=&#39;off&#39; placeholder=&#39;请输入密码&#39;>
  <input  @invalid="passwInvalid" @valid="passwok" 
  type="password" v-model=&#39;passw2&#39; id=&#39;passw2&#39; v-validate:passw2="[&#39;passw&#39;]"  
  detect-change="off" initial=&#39;off&#39; placeholder=&#39;请输入密码&#39;>
</validator>
<script>
//若是在main.js中导入  无需再次导入
//此处导入的是上面代码的validation.js
import validator from &#39;../validator/validation&#39;
export default{
    data(){
        return{
            comment:&#39;&#39;,
            passw:&#39;&#39;,
            passw2:&#39;&#39;
        }
    },
    methods:{
        passwInvalid(){
            alert(&#39;只能输入6-20个字母、数字、下划线&#39;);
        },
        passwok(){
            //alert(&#39;验证码符合规范&#39;)
        }
    }
}
</script>
登入後複製

 範例:使用者註冊驗證

用了一個元件來顯示提示訊息

toast.vue

<template>
    <div v-show="toastshow" transition="toast" 
    class="toast font-normal">
        {{toasttext}}
    </div>
</template>
<script>
export default{
    props:{
        //是否显示提示
        toastshow:{
            type:Boolean,
              required: false,
            default:function(){
                return false;
            }
        },
      //提示的内容
      toasttext:{
           type:String,
          required: false,
          default:function(){
              return &#39;no message&#39;;
           }
        },
        //显示的时间
        duration: {
            type: Number,
            default:3000,//默认3秒
            required:false
        }        
    },
    ready() {
        
    },
    watch:{
        toastshow(val){
        if (this._timeout) clearTimeout(this._timeout)
          if (val && !!this.duration) {
             this._timeout = setTimeout(()=> 
             this.toastshow = false, this.duration)
            }
        }
    }
}
</script>
<style>
    .toast{
        position:absolute;
        left:50%;
        margin-left:-25%;
        bottom:30px;
        display:block;
        width:200px;
        height:auto;
        text-align:center;
        color:white;
        background-color:rgba(0,0,0,0.5);
        border-radius:10px;
        z-index:10;
        transform:scale(1);
        padding:5px;
    }
    .toast-transition{
        transition: all .3s ease;
    }
    .toast-enter{
        opacity:0;
        transform:scale(0.1);
    }
    .toast-leave{
        opacity:0;
        transform:scale(0.1);
    }
</style>
登入後複製

註冊用戶:假如我們需要填寫手機號碼和輸入兩次密碼

<template>
   <div class=&#39;register-box&#39;>
   <!-- 组件:用于显示提示信息 -->
   <Toast :toastshow.sync="toastshow" :toasttext="toasttext"></Toast>
   <validator name="validation_register1">
    <div class=&#39;register1&#39;>
    <div class=&#39;pd05&#39;>
   <input @invalid="telonInvalid" initial="off" 
   detect-change="off" v-model="telphone" id="telphone" type="tel" 
   class=&#39;phone-number&#39; v-validate:telphone="[&#39;tel&#39;]"  
   placeholder=&#39;请输入手机号码&#39;>
    </div>
    <div class=&#39;pd05&#39;>
     <input @invalid="passwInvalid" v-model="passw1" initial="off"  
     detect-change="off" id="passw1" type="password" 
     v-validate:passw1="[&#39;passw&#39;]"class=&#39;password-number&#39;placeholder=&#39;请输入密码&#39;>
            </div>
            <div class=&#39;pd05&#39;>
            <input @invalid="passwInvalid" v-model="passw2" 
           initial="off" detect-change="off" id="passw2" type="password"
          v-validate:passw2="[&#39;passw&#39;]" class=&#39;password-number&#39; 
             placeholder=&#39;请输入密码&#39;>
         </div>
    <a class=&#39;greenBtn&#39; v-on:click=&#39;register_user()&#39;>下一步</a>
        </div>
        </validator>
    </div>
</template>
<script>
//导入validation.js  此处的validation.js就是上文中validation.js的内容
import validator from &#39;../validator/validation&#39;;
//导入显示提示信息的组件
import Toast from &#39;../components/toast.vue&#39;;
export default{    
    components: {
        //注册组件
          Toast
      },
    data(){
        return{
            telphone:&#39;&#39;,//电话号码
            toastshow:false,//默认不现实提示信息
            toasttext:&#39;&#39;,//提示信息内容
            passw1:&#39;&#39;,//首次输入密码
            passw2:&#39;&#39;//再次输入密码
        }
    },
    methods:{
        //手机号验证失败时执行的方法
        telonInvalid(){
            //设置提示信息内容
            this.$set(&#39;toasttext&#39;,&#39;手机不正确&#39;);
            //显示提示信息组件
            this.$set(&#39;toastshow&#39;,true);
        },
        //密码验证失败时执行的方法
        passwInvalid(){
          this.$set(&#39;toasttext&#39;,&#39;只能输入6-20个字母、数字、下划线&#39;);
          this.$set(&#39;toastshow&#39;,true);
        },    
        register_user(){
            var that = this;
            var telephones = that.$get(&#39;telphone&#39;);
            var pw1 = that.$get(&#39;passw1&#39;);
            var pw2 = that.$get(&#39;passw2&#39;)  
            that.$validate(true, function () {            
                if (that.$validation_register1.invalid) {
                    //验证无效
                      that.$set(&#39;toasttext&#39;,&#39;请完善表单&#39;);
                     that.$set(&#39;toastshow&#39;,true);
                }else{
       that.$set(&#39;toasttext&#39;,&#39;验证通过&#39;);
       that.$set(&#39;toastshow&#39;,true);
       //验证通过做注册请求
       /*that.$http.post(&#39;http://192.168.30.235:9999/rest/user/register&#39;,
       &#39;account&#39;:telephones,&#39;pwd&#39;:pw1,&#39;pwd2&#39;:pw2}).then(function(data){
       if(data.data.code == &#39;0&#39;){
         that.$set(&#39;toasttext&#39;,&#39;注册成功&#39;);
           that.$set(&#39;toastshow&#39;,true);
           }else{
              that.$set(&#39;toasttext&#39;,&#39;注册失败&#39;);
             that.$set(&#39;toastshow&#39;,true);
                      }
             },function(error){
               //显示返回的错误信息
              that.$set(&#39;toasttext&#39;,String(error.status));
                 that.$set(&#39;toastshow&#39;,true);
                    })*/
                }
            })
            
        }
    }
}
</script>
<style>
.register-box{
    padding: 10px;
}
.pd05{
    margin-top: 5px;
}
.greenBtn{
    width: 173px;
    height: 30px;
    text-align: center;
    line-height: 30px;
    background: red;
    color: #fff;
    margin-top: 5px;
}
</style>
登入後複製

如果點擊下一步,會提示“請完善表單”,因為驗證不通過;若是文字方塊獲得焦點後失去焦點則會提示相應的錯誤訊息;若內容填寫正確,則會提示驗證通過並發送相應的請求。

效果如圖

詳解vue驗證器(vue-validator)的使用

相關推薦:

2020年前端vue面試題大匯總(附答案)

vue教學推薦:2020最新的5個vue.js影片教學精選

更多程式相關知識,請訪問:程式設計入門! !

以上是詳解vue驗證器(vue-validator)的使用的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
vue
來源:cnblogs.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!