栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > Web开发 > JavaScript

详解vue-validator(vue验证器)

JavaScript 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

详解vue-validator(vue验证器)

官方文档: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)
});

使用验证器

验证器语法


  
  
   不得少于3个字符
   不得大于15个字符
  
 

默认情况下,vue-validator 会根据 validator 和 v-validate 指令自动进行验证。然而有时候我们需要关闭自动验证,在有需要时手动触发验证。如果你不需要自动验证,可以通过 initial 属性或 v-validate 验证规则来关闭自动验证。如下:


   
   
    不得少于3个字符
    不得大于15个字符
   

Terminal 指令问题


  
  
  



示例:用户注册验证

用了一个组件来显示提示信息

toast.vue




  .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);
  }


注册用户:假如我们需要填写手机号和输入两次密码




.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;
}


若点击下一步,会提示“请完善表单”,因为验证不通过;若是文本框获得焦点后失去焦点则会提示相应的错误信息;若内容填写正确,则会提示验证通过并发送相应的请求。

效果如图

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/90839.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号