如何仅验证Vee-validate3.x中的某些字段



版本:Vee validate 3.x

有时我只想验证一些字段,有时我想验证所有字段。如何使用ValidationObserver?

<template>
<ValidationObserver  ref="validationObserver">
<form>
<ValidationProvider name="E-mail" rules="required|email" v-slot="{ errors }">
<input v-model="email" type="email">
<span>{{ errors[0] }}</span>
</ValidationProvider>
<ValidationProvider name="First Name" rules="required|alpha" v-slot="{ errors }">
<input v-model="firstName" type="text">
<span>{{ errors[0] }}</span>
</ValidationProvider>
<ValidationProvider name="Last Name" rules="required|alpha" v-slot="{ errors }">
<input v-model="lastName" type="text">
<span>{{ errors[0] }}</span>
</ValidationProvider>

</form>
</ValidationObserver>
<button @click="validateSome">validateSome</button>
<button @click="validateAll">validateAll</button>
</template>
<script>
export default {
methods:{
validateAll(){
this.$refs.validationObserver.validate().then(isOk=>console.log(isOk))
}
validateSome(){
// if i want to validate only [email,firstName] fields, how can i do ?
}
}
}
</script>

如何完成validateSome方法?

您实际上可以嵌套Validation Observer!因此,有时可以尝试在另一个ValidationObserver中分别包装要验证的两个字段,给它一个ref,并以在validateAll中调用外部字段的方式调用它。

<ValidationObserver ref="validationObserver">
<form>
<ValidationObserver ref="innerObs">
<ValidationProvider name="E-mail" rules="required|email" v-slot="{ errors }">
<input v-model="email" type="email">
<span>{{ errors[0] }}</span>
</ValidationProvider>
<ValidationProvider name="First Name" rules="required|alpha" v-slot="{ errors }">
<input v-model="firstName" type="text">
<span>{{ errors[0] }}</span>
</ValidationProvider>
</ValidationObserver>
<ValidationProvider name="Last Name" rules="required|alpha" v-slot="{ errors }">
<input v-model="lastName" type="text">
<span>{{ errors[0] }}</span>
</ValidationProvider>
</form>
</ValidationObserver>

然后你的功能是这样的:

validateSome(){
this.$refs.innerObs.validate().then(isOk=>console.log(isOk))
}

相关内容

  • 没有找到相关文章

最新更新