【vue】vee-validate 表单验证详解

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/dangbai01_/article/details/84786814

Pre:安装

npm install [email protected]

内置的校验规则

  • after{target} - 比target要大的一个合法日期,格式(DD/MM/YYYY)

  • alpha - 只包含英文字符

  • alpha_dash - 可以包含英文、数字、下划线、破折号

  • alpha_num - 可以包含英文和数字

  • before:{target} - 和after相反

  • between:{min},{max} - 在min和max之间的数字

  • confirmed:{target} - 必须和target一样

  • date_between:{min,max} - 日期在min和max之间

  • date_format:{format} - 合法的format格式化日期

  • decimal:{decimals?} - 数字,而且是decimals进制

  • digits:{length} - 长度为length的数字

  • dimensions:{width},{height} - 符合宽高规定的图片

  • email - 不解释

  • ext:[extensions] - 后缀名

  • image - 图片

  • in:[list] - 包含在数组list内的值

  • ip - ipv4地址

  • max:{length} - 最大长度为length的字符

  • mimes:[list] - 文件类型

  • min - max相反

  • mot_in - in相反

  • numeric - 只允许数字

  • regex:{pattern} - 值必须符合正则pattern

  • required - 不解释

  • size:{kb} - 文件大小不超过

  • url:{domain?} - (指定域名的)url

使用:

1.main.js添加

import Vue from 'vue'

import VeeValidate, {Validator}  from 'vee-validate';

import zh from 'vee-validate/dist/locale/zh_CN';

Validator.addLocale(zh);

const config = {

  locale: 'zh_CN'

};

Vue.use(VeeValidate,config);

2.一个例子:

    <p>

        <input v-validate="'required|email'" name="email" type="text" placeholder="Email">

        <span v-show="errors.has('email')"  >{{ errors.first('email') }}</span>

    </p>

关于 提示:errors,它是一条json数据

{

    "errors": [

        {

            "field": "email",

            "msg": " email 必须是有效的邮箱.",

            "rule": "email",

            "scope": "__global__"

        }

    ]

}

==>errors.has('email’)//当前email是否有错误

==>errors.first('email’)//获取关于当前field的第一个错误信息,msg

当然,还有其他获取方式

collect('email') -- 获取关于当前field的所有错误信息(msg_list,如果有那么多的话)

all() -- 当前表单所有错误(list)

any() -- 当前表单是否有任何错误(true/false)

3.自定义校验规则

(1)添加自定义规则

//自定义规则——手机号码判断

const isMobile = {

    messages: {

        zh_CN:field => field + '必须是11位手机号码',//field 就是自定义规则的名字

    },

    validate: (value, args) => {

       return value.length == 11 && /^((13|14|15|17|18)[0-9]{1}\d{8})$/.test(value)

    }

}

Validator.extend('mobile', isMobile);//相当于起了个别名


 

(2)更新规则提示信息

const dictionary = {

   zh_CN: {

    messages: {

      mobile: () => '这个手机号有毒'

    },

    attributes:{

      mobile:'--修改默认为空字段--'

    }

  }

};

Validator.updateDictionary(dictionary);

(3)为空时候的默认提示的修改

const dictionary = {

   zh_CN: {

    messages: {

      mobile: () => '这个手机号有毒',

      required:(field)=> "请输入"+field

    },

    attributes:{

      //mobile:'--修改默认为空字段--'

    }

  }

};

Validator.updateDictionary(dictionary);

(4)使用

      <div>

        <input v-validate="'required|mobile'" name="mobile" type="text" placeholder="mobile">

        <span v-show="errors.has('mobile')"  >{{ errors.first('mobile') }}</span>

      </div>

猜你喜欢

转载自blog.csdn.net/dangbai01_/article/details/84786814
今日推荐