vue2多文本框的表单校验(1)-提交时才校验
1,交互
点击提交时才校验,若校验不通过则报错;
再次开始输入,则 错误提示消失
失去焦点不校验
2,效果
3,实现
第一步,封装 一个自定义的组件
这个组件包括输入框和显示错误信息的 span
名称:src/components/input/ValidateInput.vue
内容如下:
<template>
<div>
<input
@input="inputAction($event.target.value)"
v-bind:name="nam" :value="value" class="inf-input" :class="className"
type="text" :placeholder="placeholder"
autocomplete="off"/>
<span v-show=" haserror " class="warning fz12">{{ errormessage}}</span>
</div>
</template>
<script>
import sharedStateMixin from '@/services/status/sharedState.mixin'
export default {
mixins: [sharedStateMixin],
props: ['nam', 'className', 'value', 'v_validate', 'data_vv_as', 'placeholder', 'haserror', 'errormessage', 'clicksubmit'],
methods: {
inputAction: function (val2) { //keyup
// this.val = val2
// this.value = val2
this.$emit('input', val2)
console.log('this.value', this.value)
this.sharedState.bus.$emit('clearInputError',this.nam);
}
}
}
</script>
:value=value
和 this.$emit('input') 都是为了实现组件的v-model功能
说明:为了输入时清空错误,使用 eventbus
@input 相当于纯js中的 keyup
第二步,在父组件中调用
<validate-input :haserror="errors.has('invoice_phone')" :errormessage="errors.first('invoice_phone')"
data-vv-name="invoice_phone" nam="invoice_phone"
data-vv-value-path="value"
v-validate="'required|mobile'"
data-vv-as="手机号"
placeholder="请填写签收人手机号" v-model="invoice_dto.deliverPhone" ></validate-input>
第三步,提交时校验:
this.$validator.validateAll().then((validateFlag) => {
console.log('validateFlag', validateFlag)
if (!validateFlag && (!this.invoice_dto.invoicePersonal)) {
console.log('校验失败!!!')
return
}
console.log('校验通过...')
// this.$validator.reset()
//校验成功,则发送http请求
this.updateInvoice(this.invoice_dto)
}, err => {
console.log('校验报错!!!!!')
console.log(err)
});
第四步,父组件中注册 eventbus:
created: function () {
console.log('created')
this.sharedState.bus.$on('clearInputError',function (name) {
console.log('clear error:',name)
this.errors && this.errors.remove(name)
}.bind(this))
}
注意:
this.errors.remove 是清除指定字段的错误
this.errors.clear 是清除全部字段的错误
参考:http://vee-validate.logaretm.com/api.html#error-bag