我将组合API与Vue 2(通过使用@vue/composition-api)和以下两个库(@vuelidate/core": "^2.0.0-alpha.18,@vuelidate/validators": "^2.0.0-alpha.15)结合使用。
我正在尝试使用sameAs检查输入的电子邮件和重复的电子邮件是否匹配,如果不匹配则返回错误。尽管这并不像预期的那样顺利。
这是我的validation.js文件
import { required, email, maxLength, sameAs } from "@vuelidate/validators";
export default {
email: {
required,
email,
maxLength: maxLength(100),
},
repeatEmail: {
required,
email,
maxLength: maxLength(100),
sameAsEmail: sameAs('email')
},
}这是我的validation-errors.js文件。(可能与这个问题无关)
export default {
email: [
{
key: "required",
message: "Email is required.",
id: "emailRequired",
},
{
key: "email",
message: "Wrong format on your email.",
id: "emailFormat",
},
{
key: "maxLength",
message: "Email can't be longer than 100 characters.",
id: "emailLength",
},
],
repeatEmail: [
{
key: "required",
message: "Email is required.",
id: "emailRequired",
},
{
key: "email",
message: "Wrong format on your email.",
id: "emailFormat",
},
{
key: "maxLength",
message: "Email can't be longer than 100 characters.",
id: "emailLength",
},
{
key: "sameAsEmail",
message: "Email isn't matching.",
id: "sameAsEmailFormat",
},
],
}这就是我试图在我的组件中使用它的方式。
import validations from "@/validation";
import validationErrors from "@/validation-errors";
import { useVuelidate } from "@vuelidate/core";
import { reactive, toRefs } from '@vue/composition-api';
export default {
setup() {
const state = reactive({
email: "",
repeatEmail: "",
});
const $v = useVuelidate(validations, state);
return {
...toRefs(state)
}
}
}因此,当我在电子邮件和repeatEmail的输入域中输入相同的值时,它会给我一个无效值true。
发布于 2021-06-11 22:16:27
内置的验证器,比如sameAs don't have access to the state,,所以当像sameAs('email')一样使用时,它们是不能工作的。
这样,验证器应该在setup函数中定义,以便访问状态:
const emailRef = computed(() => state.email);
const validations = {
...
repeatEmail: {
...
sameAsEmail: sameAs(emailRef)
},否则,这需要使用自定义验证器来完成,而不是使用getCurrentInstance访问组件实例上的状态的内置验证器。
https://stackoverflow.com/questions/67938208
复制相似问题