ReactJS:使用Formik多步骤表单,验证不适用于Yup

时间:2019-05-17 11:23:58

标签: reactjs formik yup

我有一个多步骤表单,其中使用了FormikYup库。

但是我正在使用的yup库的验证根本不起作用。在React调试器工具中,我得到的值为空。因此,无论我在输入字段中写入什么内容,它都将使用“ Required”消息进行验证,因为其值为空。

import { Formik, Form, Field, ErrorMessage } from 'formik';
import * as Yup from 'yup';

let accountInfoSchema = Yup.object().shape({
  name: Yup.string()
  .max(20, 'Too Long!')
  .required('Name is Required'),
});

class AccountInfo extends Component {
 handleChange = event => {
    this.setState({    
      userAccountData: Object.assign(
        {}, 
        this.state.userAccountData,
        { [event.target.name]: event.target.value }
      ),
    })
  }

 AccountInfoView = () => {
    return (
      <section className="form">
      <React.Fragment>
        <Formik
          initialValues={{name:'' }}
          validationSchema={accountInfoSchema}
          render={() => {
          return(
        <Form onSubmit={this.handleSubmit}>
        {this.Step1()}
        {this.Step2()}
        {this.Step3()}
        <li className="stb_btn half">
          <div className="custom_group">
            {this.previousButton()}
          </div>
        </li>
        <li className="stb_btn half">
          <div className="custom_group">
            {this.nextButton()}
          </div>
        </li>
        </Form>
        );
      }}
      />
      </React.Fragment>
      </div>
    </section>
    )
  }

Step1 = () => {
return(
<li>
   <div className="custom_group">
   <Field type="text" name="name" className="trans text_input" placeholder="Enter your name" value={this.state.userAccountData['name']} onChange={this.handleChange} />
   <label className="label_two">Name</label>
   <ErrorMessage name="name" />
   </div>
 </li>
)
}

render() {    

    return (
      <div>{this.AccountInfoView()}</div>
    )
  }


}

请检查反应控制台响应,该值为空。

enter image description here

1 个答案:

答案 0 :(得分:1)

之所以无法进行验证,是因为您要传递到Field this.state.userAccountData['name']onChange={this.handleChange}

Formik已经具有一种状态,可以存储表单中的所有数据,您无需将其保持在组件状态。

在字段中添加onChange={this.handleChange}时,您更改了组件的状态,但不更改Formik的状态,这就是为什么验证不会触发的原因。

我不确定您为什么要保持name的状态,但是如果您没有任何理由认为不必要的话。

 // formik already handle the state for you inside `values`
 handleChange = event => {
    this.setState({    
      userAccountData: Object.assign(
        {}, 
        this.state.userAccountData,
        { [event.target.name]: event.target.value }
      ),
    })
  }

// Formik already handles the value and the onChange of the input
<Field type="text" name="name" className="trans text_input" placeholder="Enter your name" value={this.state.userAccountData['name']} onChange={this.handleChange} />

您唯一需要做的就是设置字段的name属性,使其与验证匹配。

// this is enough
<Field type="text" name="name" className="trans text_input" placeholder="Enter your name" />