问题
I am trying to create some custom error messages with Yup to determine if the user's email address is in use.
I have created the following promise to try and catch a server communication error:
.test(
{
name: 'Email Check',
test: value => {
if (value.includes("@")) {
return new Promise<yup.ValidationError>((resolve, reject) => {
let client = new RegistrationApi();
client.emailCheck(value,
x => x ? resolve(undefined) : resolve(new yup.ValidationError("E-mail address already used", value, "")),
() =>resolve(new yup.ValidationError("Failed to contact server", value, "")),
undefined);
});
}
else {
return false;
}
}
}),
Returning the validation errors doesn't result in any error message being displayed. What am I doing wrong? I have tried to use the createError method which seems to be details in examples, but it doesn't seem to exist in this context.
回答1:
Regarding your code, you will want to reject
your Promise and not resolve
it.
generally; you need to return a promise to the validation function of your yup schema. Or you can write a specific async test.
回答2:
createError
needs to be used inside of a function declaration for the test method. You are currently using an arrow function.
来源:https://stackoverflow.com/questions/60154861/dynamic-validation-messages-using-yup-and-typescript