yup如何验证最小年龄?

ivi*_*oke 1 reactjs react-native yup formik

我创建了一些registrationSchema

 export const registrationSchema = (translate) => Yup.object().shape({
  //... other properties that are validated.
  //       for example username
    username: Yup.string()
    .min(6, translate('validation:common.username.min', { min: 6 }))
    .max(20, translate('validation:common.username.max', { max: 20 }))
    .required(translate('validation:common.username.required')),
     DOB: Yup.lazy(value => {
        console.log('yup', value);
        if (moment().diff(moment(value), 'years') < 18)
          // Here return DOB error somehow
      })
    ...
Run Code Online (Sandbox Code Playgroud)

到目前为止,它的工作原理就像是一种魅力。但是现在我需要验证用户是否年满18岁。我从日期选择器中获取DateOfBirth,并且可以随时检查它是否小于18。

if(moment().diff(moment(date),'years) < 18)
Run Code Online (Sandbox Code Playgroud)

这个日期值是我在使用Yup.lazy时获得的,但是如果在18年以下才能在DOB字段中显示它,则不知道如何抛出验证错误。我什至不知道我是否使用正确的yup方法。我想使用yup.date()。但是如何在架构中获取选择日期以检查其有效年龄。

Bab*_*boo 6

您可以这样使用Yup.string

Yup.string().test(
  "DOB",
  "error message",
  value => {
    return moment().diff(moment(value),'years') >= 18;
  }
)
Run Code Online (Sandbox Code Playgroud)

如果测试函数返回true,则字段通过测试。否则设置错误。

  • 另外,如果您在第三个参数中使用普通的“function(value) { ... }”(而不是箭头函数),您可以访问特殊的“this”上下文,它允许您执行诸如返回自定义值之类的操作错误消息:“return this.createError({ message: 'Your custom message' });”,适用于根据值的不同可能会出现不同错误消息的情况。 (2认同)