简体   繁体   中英

how to validate formsection in react js using redux form?

I am trying to validate my form using redux form library. I have a form section in which there are two fields like firstname (which is required). I want to show an error when the user clicks a button.

I tried like this https://codesandbox.io/s/green-frost-414qi

const validateGeneral = general => {
  console.log(general, "general");
  let errors = {};
  // validate address.street etc
  if (general && !general.firstName) {
    errors.firstName = "enter a valid street";
  }
  return errors;
};
const validate = values => {
  console.log(values, "ddd");
  const errors = {};
  errors.general = validateGeneral(values.general);
  return errors;
};

It should show the error message when firstname is empty on button click.

You should add validate prop of the Field component provided by redux-form.

In the codesandbox example above, add validate prop as shown below, it'll work properly.

<Field
  name={i.name}
  component={i.component}
  options={i.options || undefined}
  type={i.type}
  validate={i.validate}
/>

You should include a validate prop as follows then it will show the error message when fields are empty and the button is clicked

const required = value =>
  value || typeof value === "number" ? undefined : "Required";

 <Field
  name = { i.name }
  component = { i.component }
  options = { i.options || undefined }
  type = { i.type }
  validate = { required }
  />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM