搜索很久,没有发现有关于vue+VeeValidate部分校验的。自己写一个。

主要是两个场景: 1. 校验范围内,所有的字段。 2. 校验全局所有字段。主要方法: 1.validate(fields, scope)      2. validateAll(fields)

场景: 遍历得到多个列表,每一个列表都可以独立保存当前列表。在保存当前列表的时候,需要校验当前列表输入框的合法性。

代码:

 View Code

* carList: [{}, {}]

* data-vv-scope: [type='string']  属性的值的类型是 string,表示定义了一个区域,在校验的时候,通过属性值 让validator 可以找到当前应该校验的区域。

此时通过 验证器提供的方法validate(scopeName)就可以校验当前区域了。

复制代码
doSave (obj, i) {
        var _self = this
        var validateScope = 'newsletter' + i
        this.$validator.validate(validateScope + '.*').then((result) => {
          if (result) {
            //  提交数据
            _self.doSaveAfterCheck()
          }
        })
      }
复制代码
/*
errors.has(field, scope) 返回一个true / false
errors.has('actualWgh' + index, 'newsletter' + index)}"  表示验证区域是 data-vv-scope = 'newsletter' + index  验证的字段是属性 name ='actualWgh' + index
first(field,scope) 返回与特定字段关联或由选择器指定的第一条错误消息,前提是作用域将查找该范围内的消息,
*/
<div class="form-group" :class="{'has-error': errors.has('actualWgh' + index, 'newsletter' + index)}">  
<label>总重(kg) <i class="errMsg">*</i></label>
<input type="text" class="form-control" v-model.trim="p1.actualWgh" :data-vv-scope="'newsletter' + index"
v-validate="{required: true, decimal:2, min_value: 0, max_value: p1.planWgh}"
:name="'actualWgh' + index" :data-vv-as="$t('message.weight')">
<span v-show="errors.has('actualWgh' + index, 'newsletter' + index)" class="help-block">{{ errors.first('actualWgh' + index, 'newsletter' + index) }}</span>
</div>

场景2 : 页面有多个校验。当保存的时候,需要全部校验。这个场景官方提供2种方法.

复制代码
this.$validator.validate().then((result) => {
        if (result) {
          //  提交数据。
      //   result是一个boolean值。true 表示没有触发错误规则,false 表示页面有非法值,触发错误
_self.doSaveAfterCheck() } })
复制代码

 

复制代码
this.$validator.validateAll().then((result) => {
        if (result) {
          //  提交数据。
          _self.doSaveAfterCheck()
        }
      })
复制代码

 

上述两种校验全部的方法不同点在于适用场景:

validate() 可以指定校验范围内,或者是全局的 字段。而validateAll() 只能校验全局。

官方示例: 

复制代码
// validate all fields.
//  校验全局范围所有字段
validator.validate(); === validateAll() 两个方法完全一样。

// validate a field that has a matching name with the provided selector.
//  校验哪个字段? field 取name的值。
validator.validate('field');

// validate a field within a scope.
// 校验 某个域内 的某个字段。
validator.validate('scope.field');

// validate all fields within this scope.
// 校验 某个域内的所有字段。   上述例子就是用的这个。   *_* 
validator.validate('scope.*');

// validate all fields without a scope.
// 校验没有定义域内的 字段。适用场景: 校验场景分为两种: 定义域的,没有定义域。
//  当页面所有需要校验的字段,都定义了域,则这个方法会导致没有可校验的值,直接返回true validator.validate('*');

所有评论
加载评论 ...
发表评论