首页 > 解决方案 > 仅正数 - formik/yup 模式

问题描述

我做了这样一个架构:

const schema = yup.object().shape({

    seats: yup
      .number()
      .label('seats')
      .required('pls enter'),
  });

此外,我想检查该数字是正数还是大于 0。有什么方法可以将这样的条件添加到架构中?

标签: javascriptreactjstypescriptformikyup

解决方案


您可以使用该test()方法并在那里添加自定义验证:

number: Yup.number()
  .required('ERROR: The number is required!')
  .test(
    'Is positive?', 
    'ERROR: The number must be greater than 0!', 
    (value) => value > 0
  )

https://github.com/jquense/yup#mixedtestname-string-message-string--function-test-function-schema


推荐阅读