vue爬坑——vee-validate的使用

来源:互联网 发布:阿里云域名访问网站 编辑:程序博客网 时间:2024/06/10 04:52

vue爬坑——vee-validate的使用

1、npm安装vee-validate

npm install vee-validate --save

安装时要注意安装的版本,不同的版本使用的方式不一样,这里我安装的是”^2.0.0-rc.26”。
具体版本的使用见官网:vee-validate官网

2、main.js里引用vee-validate插件

import Vue from 'vue'import VeeValidate,{ Validator } from 'vee-validate'import zh_CN from 'vee-validate/dist/locale/zh_CN'Vue.use(VeeValidate);

3、vee-validate提示语汉化

//提示语汉化Validator.locale ==="en" ? "zh_CN" : "en";Validator.localize(Validator.locale,{    messages: zh_CN.messages,    attributes:{        loginName:'登录名',        loginPassword:'密码'    }});

4、验证方法扩展

Validator.extend('phone', {    getMessage: (field, [args]) => `请输入正确的手机号码`,    validate: (value, [args]) =>{        const reg = /^((13|14|15|17|18)[0-9]{1}\d{8})$/;        return reg.test(value)     }  });

5、组件中使用

<form class="form" autocomplete="off" @submit.prevent="formSubmit">  <div class="form-item">    <input type="text" placeholder="请输入手机号" v-model="loginName" name="loginName" id="loginName" v-validate.initial="'required|phone'" maxlength="11" :class="{'valid-error':errors.has('loginName')}"/>  </div>  <div class="form-item">    <input type="password" placeholder="请输入密码" v-model="loginPassword" maxlength="18" name="loginPassword" id="loginPassword" :class="{'valid-error':errors.has('loginPassword')}" v-validate.initial="'required|password'" />  </div>  <div class="form-item clearfix">    <router-link to="" class="login-link color-blue login-forget fr"><span class="iconfont icon-wenhao" replace></span>忘记密码</router-link>  </div>  <button class="form-btn bg-blue" type="submit">登录</button></form>
原创粉丝点击