仅正数-formik / yup模式

问题描述

我制定了这样的模式:

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

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

另外,我想检查该数字是否为正数或大于0。是否可以将这种条件添加到模式中?

解决方法

您可以使用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

,

实际上,Yup提供了以下功能:https://github.com/jquense/yup#numberpositivemessage-string--function-schema

,

您可以使用 .positive() 也可以使用 .min(1)

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

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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...