Dynamic Validation Messages Using Yup and Typescript

偶尔善良 提交于 2020-12-06 07:02:30

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!