美文网首页
【Vue】 使用 vuelidate 实现表单验证

【Vue】 使用 vuelidate 实现表单验证

作者: Q小予o0 | 来源:发表于2020-06-19 18:25 被阅读0次

vue中,使用vuelidate方便地实现表单验证。

[官方文档链接]https://monterail.github.io/vuelidate/

安装

使用npm安装:npm install vuelidate --save

在main.js中引入:

import Vuelidate from 'vuelidate'
Vue.use(Vuelidate)

在组件.vue中引入需要使用的验证项:

import { required, minLength, maxLength, sameAs } from 'vuelidate/lib/validators'

使用

例如我们要写一个注册时的表单验证,需要用户填写的信息有:username,phoneNumber,phoneCode,password,confirmPassword。用vuelidate对这些数据进行验证。

代码


data () {
  return {
    user: {
      username:'',
      phone: '',
      phoneCode: '',
      password: '',
      confirmPassword: '',
    },
  }
},
validations: {
  user: {
    username: {
      required,
      minLength: minLength(2),
      maxLength: maxLength(20)
    }
    phone: {
      required
    },
    phoneCode: {
      required
    },
    password: {
      required,
      minLength: minLength(8),
      maxLength: maxLength(32)
    },
    confirmPassword: {
      sameAsPassword: sameAs('Password')
    }
  }
}

html代码


<!--手机号-->
<div class="form-group" :class="{'error': $v.user.phone.$error}">
  <span class="message" v-if="!$v.user.phone.required">手机号不能为空</span>
 
  <input type="text" placeholder="手机号"
    v-model.trim="user.phone"
    @blur="$v.user.phone.$touch()">

</div>
 
<!--密码-->
<div class="form-group" :class="{'error': $v.user.password.$error}">
  <span class="message" v-if="!$v.user.password.required">密码不能为空</span>
  <span class="message"
    v-if="!$v.user.password.minLength">密码不能小于{{$v.user.password.$params.minLength.min}}位</span>
  <span class="message"
    v-if="!$v.user.password.maxLength">密码不能大于{{$v.user.password.$params.maxLength.max}}位</span>
 
  <div class="auth-password">
    <input type="password" placeholder="输入密码"
      v-model.trim="user.password"
      @blur="$v.user.password.$touch()" ref="password1">
  </div>
</div>
 
<!--确认密码-->
<div class="form-group" :class="{'error': $v.user.confirmPassword.$error}">
  <span class="message" v-if="!$v.user.confirmPassword.sameAsPassword">两次输入的密码不一样</span>
  
  <div class="auth-password">
    <input type="password" placeholder="确认密码"
      v-model.trim="user.confirmPassword"
      @blur="$v.user.confirmPassword.$touch()"
      @keyup.enter="register" ref="password2">
</div>
</div>

其中,第21行、32行中的$touch()方法,表示在什么时候执行验证。

@blur="v.user.Phone.touch()"表示blur事件触发(失去焦点)时验证。
@input="v.user.Phone.touch()"表示input事件触发(输入内容发生变化)时验证。

[原文链接]https://blog.csdn.net/latency_cheng/java/article/details/78580820

image.png

相关文章

网友评论

      本文标题:【Vue】 使用 vuelidate 实现表单验证

      本文链接:https://www.haomeiwen.com/subject/fljbxktx.html