【问题标题】:How to assign object validation in yup for react-select (single-select)如何在 yup 中为反应选择(单选)分配对象验证
【发布时间】:2019-07-22 05:20:09
【问题描述】:

我正在尝试使用 yup 概念实现对反应选择(单选)的验证。但是我收到了这个错误:

对象作为 React 子对象无效(找到:带有键 {label, value} 的对象)。如果您打算渲染一组子项,请改用数组。

我想知道如何在验证模式中为 yup 概念分配对象

<Formik
  initialValues={{
    department:"",
  }}
  onSubmit={this.submitForm}
  validationSchema={Yup.object().shape({
    department: Yup.object().shape({
      label: Yup.string().required(),
      value: Yup.string().required(),
    }),
})}>
{ props => {
  const {
    values,
    touched,
    errors,
    isSubmitting,
    handleChange,
    handleBlur,
    handleSubmit,
    selectedOption
  } = props;
  return (
    <React.Fragment>

    <InputLabel shrink htmlFor={'department'}>
    Department</InputLabel>
    <Select
          inputId="department"
          options={options}
          value={values.department}
          onChange={this.onChangeOption}
          onBlur={handleBlur}         
       />
{errors.department && touched.department && ( {errors.department} )} 
Submit </div> </React.Fragment> ); }} 

【问题讨论】:

  • 这种方法是否有效。卡在同一个地方

标签: reactjs react-select formik yup


【解决方案1】:

我想知道如何在验证模式中为 yup 概念分配对象

你做得对(据我所知):

validationSchema={Yup.object().shape({
  department: Yup.object().shape({
    label: Yup.string().required(),
    value: Yup.string().required(),
  })
}

React 抱怨的是这一行:

{errors.department && touched.department && ( {errors.department} )} 

如果errors 有一个名为department 的键,并且如果touched 有一个名为department 的键,则此评估结果是,然后渲染对象errors.department。 React 无法做到这一点。如果您想显示错误,我建议您在选择之外为其设置一个专用组件(例如&lt;p&gt; 标签)。像这样的:

{errors.department && touched.department && (<p>{errors.department.label}</p>)}

你可以为value做类似的事情。

PS:您的代码似乎不完整且格式不正确(例如,有一个浮动的&lt;div /&gt; 标签)。

【讨论】:

    【解决方案2】:

    您可以使用nullable()required() 优化形状架构。

    例子

    const requiredOption = Yup.object()
      .shape({
        value: Yup.string(),
        label: Yup.string(),
      })
      .nullable()
      .required('This field is required.');
    

    为什么要nullable()required() 给形状!

    1. 如果输入获得焦点并且用户决定跳过输入,则该输入的值仍设置为 null 并触发验证。最终,您会遇到这样的错误。

    输入必须是object 类型,但最终值为:null。如果 “null”旨在作为空值确保将架构标记为 .nullable()

    1. 如果您确定所有属性都是必需的,则可以直接在对象形状上调用所需的函数,而不是对形状模式的各个属性进行要求。

    【讨论】:

      猜你喜欢
      • 2021-03-20
      • 2020-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-21
      • 2021-09-21
      • 2021-09-21
      • 2013-01-28
      相关资源
      最近更新 更多