yup如何验证最小年龄?

时间:2019-02-26 14:58:08

标签: reactjs react-native formik yup

我创建了一些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
      })
    ...

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

if(moment().diff(moment(date),'years) < 18)

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

1 个答案:

答案 0 :(得分:3)

您可以像这样使用past_loc

Yup.string

如果测试函数返回Yup.string().test( "DOB", "error message", value => { return moment().diff(moment(value),'years') >= 18; } ) ,则字段通过测试。否则设置错误。

相关问题