Vue 使用 vuelidate 实现表单验证

表单验证的应用场景十分广泛,因为网站对用户输入内容的限制是非常必要的。
在vue中,我们使用vuelidate方便地实现表单验证。

官方文档在这里https://monterail.github.io/vuelidate/

1、安装

    • 使用npm安装:npm install vuelidate --save
    • 在main.js中引入:
import Vuelidate from 'vuelidate'
Vue.use(Vuelidate)

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

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

 2、使用
例如我们要写一个注册时的表单验证,需要用户填写的信息有:username,phoneNumber,phoneCode,password,confirmPassword。用vuelidate对这些数据进行验证。代码很容易懂,就不写多余的说明了。
.vue中的代码如下:

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/article/details/78580820

猜你喜欢

转载自www.cnblogs.com/yunspider/p/9315338.html