【问题标题】:Yup: how to compare the current value against the initial value in a `test`是的:如何将当前值与“测试”中的初始值进行比较
【发布时间】:2020-06-28 13:41:27
【问题描述】:

你能以某种方式创建一个.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

【问题讨论】:

    标签: yup


    【解决方案1】:

    我最终为架构创建了一个工厂,如下所示:

    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 }); 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-27
      • 2015-03-12
      • 1970-01-01
      • 1970-01-01
      • 2022-08-23
      相关资源
      最近更新 更多