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事件触发(输入内容发生变化)时验证。


上面只列举了vuelidate中最基本的一些表单验证,复杂的有机会再来补上。




  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值