VeeValidate表单校验

1,073 阅读1分钟

  1. 在项目中安装

    npm install vee-validate@2.0.0-rc.25 --save

    注意:如果不指定版本直接安装,会出错,是因为版本不存在

  2. 在项目中引入

    // main.js
    import VeeValidate from 'vee-validate';
    Vue.use(VeeValidate);
    
  3. 自定义校验规则

    1、在项目根目录新建_rules.js 文件
    2、在main.js 中引入  import './_rule.js'
    
    // 下面是_rules.js中的代码
    import { Validator } from 'vee-validate';
    
    Validator.extend('userName',{
        getMessage:field => '不能以_开头',
        validate: value => {
            return /\^[-]/.test(value)
        }
    })
    Validator.extend('password',{
        getMessage:field => '只能包含字母、数字、下划线、长度 6-20',
        validate: value => {
            return /^(\w){6,20}$/.test(value) // 只能包含字母、数字、下划线、长度 6-20
        }
    })
    
  4. 在表单中使用

    <template>
        <div>
            <div>
                <label>用户名:</label>
                <input v-validate="'required|userName'" type="text" name="userName" data-vv-as="user name">
                <span v-show="errors.has('userName')">{{ errors.first('userName') }}</span>
            </div>
            <div>
                <label>密 码:</label>
                <input v-validate="'required|password'" type="password" name="password" data-vv-as="password">
                <span v-show="errors.has('password')">{{ errors.first('password') }}</span>
            </div>
            <div>
                <button @click="submitForm">提交</button>
            </div>
        </div>
    </template>
    
  5. 在点击提交按钮时进行表单校验

     submitForm() {
     	this.$validator.validateAll().then(res => {
     		console.log('提交表单',res)
    	})
     }
    

data-vv-as:

当为这个输入生成任何错误消息时,默认使用 name 对应的值,但是当 data-vv-as 存在的时候,data-vv-as 的值,将取代name的值

v-validate

将验证添加到指定的表单输入框中,并确保您的输入具有name用于生成错误消息的属性。 然后,传递给指令一个rules字符串

该文章仅用于帮助初次接触 VeeValidate的朋友们,有任何不足之处,请指正