[英]Problems with validation before submit
I'm trying to get an example from the VeeValidate docs to work.我正在尝试从 VeeValidate 文档中获取一个示例来工作。 It can be found here .
可以在这里找到。 I'm clearly missing something but I don't know what.
我显然错过了一些东西,但我不知道是什么。
My form is always valid, even though I'm not adding any text to the inputs.我的表单始终有效,即使我没有在输入中添加任何文本。 Do I need to customise the required rule somehow?
我是否需要以某种方式自定义所需的规则? CodeSandbox
代码沙盒
<template>
<ValidationObserver ref="observer" v-slot="{ invalid }" tag="form" @submit.prevent="submit()">
<input type="text" rules="required">
<br>
<input type="text" rules="required">
<br>
<button :disabled="invalid">Submit</button>
</ValidationObserver>
</template>
<script>
import { ValidationObserver } from "vee-validate";
export default {
components: {
ValidationObserver
},
methods: {
async submit() {
const isValid = await this.$refs.observer.validate();
console.log("Form is valid", isValid);
if (!isValid) {
// ABORT!!
}
// 🐿 ship it
}
}
};
</script>
Each input needs to be wrapped in a ValidationProvider
.每个输入都需要包装在
ValidationProvider
。 Change this:改变这个:
<input type="text" rules="required">
To this:对此:
<ValidationProvider rules="required">
<input type="text" rules="required" v-model="something">
</ValidationProvider>
Additionally, somewhere, you need to actually define the rules you want to use, so at the top of the file I put this:此外,在某处,您需要实际定义要使用的规则,因此我在文件顶部放置了以下内容:
import { ValidationObserver, ValidationProvider, extend } from "vee-validate";
import { required } from 'vee-validate/dist/rules';
extend('required',required);
Working copy of your Code Sandbox (I also updated vee-validate and vue to the latest versions): https://codesandbox.io/s/vue-template-dj9jn您的代码沙箱的工作副本(我还将 vee-validate 和 vue 更新为最新版本): https : //codesandbox.io/s/vue-template-dj9jn
To actually get the behaviour mentioned in the example, instead of using the invalid
flag of ValidationObserver
, try using the handleSubmit
method like so:要实际获得示例中提到的行为,请尝试使用
handleSubmit
方法,而不是使用ValidationObserver
的invalid
标志,如下所示:
<ValidationObserver tag="form" v-slot="{handleSubmit}" @submit.prevent>
...
<button @click="handleSubmit(submit)">Submit</button>
And your submit function would look like this:您的提交功能如下所示:
submit() {
//anything you do here will only be called when the form is valid
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.