gpt4 book ai didi

是的:如何将当前值与 `test` 中的初始值进行比较

转载 作者:行者123 更新时间:2023-12-05 06:19:46 25 4
gpt4 key购买 nike

你能以某种方式创建一个可以访问给定字段初始值的.test

例如,异步“电子邮件是否可用”验证,其中初始电子邮件值应被视为有效

const schema = Yup.object({
email: Yup.string()
.test('isAvailableAsync', 'The provided email is not available', async function (newValue) {
// with alias the value is undefined
// const initial = this.parent.emailInitial;

const initial = this.parent.initialEmailRef; // it's always the same with `newValue`

// email unchanged no need to do async call
if (newValue == initial) return true;

const result = await myAsyncCheck(email);
return result.exists == false;
})
initialEmailRef: Yup.ref('email'), // tried with ref
})
.from('email', 'emailInitial', true) // tried with alias

最佳答案

我最终为模式创建了一个工厂,像这样:

const getMySchema = ({ initialEmail }) => Yup.object({
email: Yup.string()
.test('isAvailableAsync', 'The provided email is not available', async (newValue) => {
// email unchanged or returned to initial value no need to do async call
if (newValue == initialEmail) return true;

const result = await myAsyncCheck(email);
return result.exists == false;
})
})

然后像这样使用它:

const schema = getMySchema({ initialEmail: user.email }); 

关于是的:如何将当前值与 `test` 中的初始值进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60722996/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com