使用诸如user.name之类的字段名称时,Redux Form Validation错误

时间:2018-09-05 11:31:47

标签: reactjs validation redux redux-form

我有一个具有redux形式的react组件

<div className="col-sm-12">
 <div className="form-group row">
  <div className="col-sm-4">
   <label>A. Name</label>
  </div>
  <div className="col-sm-8">
  <ul className="sub-qn-ans-list d-flex list-unstyled">
    <li>
      <Field
      name="first_name"
      component={renderField}
      type="text"
      placeholder="First name"
      className="form-control" />
    </li>
    <li>
      <Field
      name="last_name"
      component={renderField}
      placeholder="Last name"
      type="text"
      className="form-control" />
    </li>
  </ul>
</div>
</div>
<div className="form-group row">
<div className="col-sm-4">
  <label>B. Residential Address</label>
</div>
<div className="col-sm-8">
  <ul className="sub-qn-ans-list d-flex list-unstyled">
    <li>
      <Field
        name="residential.street"
        component={renderField}
        placeholder="Street"
        type="text"
        className="form-control" />
    </li>
    <li>
      <Field
        name="residential.area"
        component={renderField}
        placeholder="Area"
        type="text"
        className="form-control" />
    </li>
    <li>
      <Field
        name="residential.city"
        component={renderField}
        placeholder="City"
        type="text"
        className="form-control" />
    </li>
    <li>
      <Field
        name="residential.district"
        component={renderField}
        placeholder="District"
        type="text"
        className="form-control" />
    </li>
    <li>
      <Field
        name="residential.landline"
        component={renderField}
        placeholder="Landline"
        type="text"
        className="form-control" />
    </li>
    <li>
      <Field
        name="residential.mobile"
        component={renderField}
        placeholder="Mobile"
        type="text"
        className="form-control" />
    </li>
  </ul>
</div>
</div>
</div>

我正在尝试对输入字段进行验证。对字段first_namelast_name的验证工作正常。但是,当我尝试对residential.street进行验证时出现错误。

下面是我的验证代码。

const LocatorValidation = (values, form) => {
const errors = {};
if (!values.first_name) {
  errors.first_name = 'Required';
} else if (!/[A-Za-z.]+/.test(values.first_name)) {
  errors.first_name = 'First name must have only alphabets';
}
if (!values.last_name) {
  errors.last_name = 'Required';
} else if (!/^[A-Za-z.]+$/.test(values.last_name)) {
  errors.last_name = 'First name must have only alphabets';
}
if (!values.residential) {
  errors.residential.street = 'Required';
}
return errors;
}

export default LocatorValidation;

这是显示错误的图像。 enter image description here

1 个答案:

答案 0 :(得分:0)

由于#NA中的错误状态,errors.residential.street的{​​{1}}属性未定义。因此,您需要先将其设置为空对象

residential

我也会改进支票

errors