欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 前端技术 > vue >内容正文

vue

vue2移动端使用vee-validate进行表单验证

发布时间:2025/3/21 vue 44 豆豆
生活随笔 收集整理的这篇文章主要介绍了 vue2移动端使用vee-validate进行表单验证 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

使用vee-validate时若要使用中文版本提示时,vee-validate的版本需要注意

"vee-validate": "2.0.0-rc.25"

在main.js里添加如下代码

import VeeValidate, { Validator } from 'vee-validate' import CN from 'vee-validate/dist/locale/zh_CN.js' Validator.addLocale(CN) Vue.use(VeeValidate, {locale: 'zh_CN' })

若想修改默认的提示

// 修改默认错误提示 const dictionary = {zh_CN: {messages: {email: () => '邮箱格式不正确哦',required: (val) => {let msg = ''switch (val) {case 'email':msg = '邮箱'breakcase 'qq':msg = 'qq'breakdefault:;}msg = msg + '不能为空哦'return msg}}} } Validator.updateDictionary(dictionary)

自定义校验规则如下:

Validator.extend('qq', {messages: {zh_CN: field => 'qq号码输入不正确'},validate: value => {return /^[1-9][0-9]{4,14}$/.test(value)} })

以上代码写在js里。组件内进行表单验证的代码如下

<template><div class="hello"><form @submit.prevent="validateBeforeSubmit"><div class="column is-12"><label class="label" for="email">Email</label><p :class="{ 'control': true }"><input v-validate="'required|email'" v-model="email" :class="{'input': true, 'is-danger': errors.has('email') }" name="email" type="text" placeholder="Email"><span v-show="errors.has('email')" class="help is-danger">{{ errors.first('email') }}</span></p></div><div class="column is-12"><label class="label" for="qq">qq</label><p :class="{ 'control': true }"><input v-validate="'required|qq'" :class="{'input': true, 'is-danger': errors.has('qq') }" name="qq" type="text" placeholder="qq"><span v-show="errors.has('qq')" class="help is-danger">{{ errors.first('qq') }}</span></p></div><div class="column is-12"><p class="control"><button class="button is-primary" type="submit">Submit</button></p></div></form></div> </template><script> export default {name: 'HelloWorld',data () {return {email: '',qq: ''}},methods: {validateBeforeSubmit () {this.$validator.validateAll().then((result) => {if (result) {// eslint-disable-next-linealert('Form Submitted!');return}alert('Correct them errors!')})}} } </script>

 

转载于:https://www.cnblogs.com/nanacln/p/8758711.html

总结

以上是生活随笔为你收集整理的vue2移动端使用vee-validate进行表单验证的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。