搜尋
首頁web前端Vue.js詳解vue驗證器(vue-validator)的使用

詳解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中文網其他相關文章!

陳述
本文轉載於:博客园。如有侵權,請聯絡admin@php.cn刪除
Vue常见面试题汇总(附答案解析)Vue常见面试题汇总(附答案解析)Apr 08, 2021 pm 07:54 PM

本篇文章给大家分享一些Vue面试题(附答案解析)。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。

5 款适合国内使用的 Vue 移动端 UI 组件库5 款适合国内使用的 Vue 移动端 UI 组件库May 05, 2022 pm 09:11 PM

本篇文章给大家分享5 款适合国内使用的 Vue 移动端 UI 组件库,希望对大家有所帮助!

vue中props可以传递函数吗vue中props可以传递函数吗Jun 16, 2022 am 10:39 AM

vue中props可以传递函数;vue中可以将字符串、数组、数字和对象作为props传递,props主要用于组件的传值,目的为了接收外面传过来的数据,语法为“export default {methods: {myFunction() {// ...}}};”。

手把手带你利用vue3.x绘制流程图手把手带你利用vue3.x绘制流程图Jun 08, 2022 am 11:57 AM

利用vue3.x怎么绘制流程图?下面本篇文章给大家分享基于 vue3.x 的流程图绘制方法,希望对大家有所帮助!

聊聊vue指令中的修饰符,常用事件修饰符总结聊聊vue指令中的修饰符,常用事件修饰符总结May 09, 2022 am 11:07 AM

本篇文章带大家聊聊vue指令中的修饰符,对比一下vue中的指令修饰符和dom事件中的event对象,介绍一下常用的事件修饰符,希望对大家有所帮助!

如何覆盖组件库样式?React和Vue项目的解决方法浅析如何覆盖组件库样式?React和Vue项目的解决方法浅析May 16, 2022 am 11:15 AM

如何覆盖组件库样式?下面本篇文章给大家介绍一下React和Vue项目中优雅地覆盖组件库样式的方法,希望对大家有所帮助!

通过9个Vue3 组件库,看看聊前端的流行趋势!通过9个Vue3 组件库,看看聊前端的流行趋势!May 07, 2022 am 11:31 AM

本篇文章给大家分享9个开源的 Vue3 组件库,通过它们聊聊发现的前端的流行趋势,希望对大家有所帮助!

react与vue的虚拟dom有什么区别react与vue的虚拟dom有什么区别Apr 22, 2022 am 11:11 AM

react与vue的虚拟dom没有区别;react和vue的虚拟dom都是用js对象来模拟真实DOM,用虚拟DOM的diff来最小化更新真实DOM,可以减小不必要的性能损耗,按颗粒度分为不同的类型比较同层级dom节点,进行增、删、移的操作。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
2 週前By尊渡假赌尊渡假赌尊渡假赌
倉庫:如何復興隊友
4 週前By尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island冒險:如何獲得巨型種子
4 週前By尊渡假赌尊渡假赌尊渡假赌

熱工具

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )專業的PHP整合開發工具

Dreamweaver Mac版

Dreamweaver Mac版

視覺化網頁開發工具

SecLists

SecLists

SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。