简体   繁体   中英

react-hook-form validation not working with custom fields array

I am using react-hook-form with custom dynamic input fields array, it looks like the validation is working when I click on submit button, but it doesn't show the error messages, I am creating the state as:

const [formFields, setFormFields] = useState([
{
  height: 45,
  label: "tv",
  placeholder: "555",
  name: "tv",
  maxWidth: 203,
  error: errors.tv,
  value: ""
},
{
  height: 45,
  label: "radio",
  placeholder: "90%",
  name: "radio",
  maxWidth: 126,
  error: errors.radio,
  value: ""
},
{
  height: 45,
  label: "instagram",
  placeholder: "90%",
  name: "instagram",
  maxWidth: 126,
  error: errors.instagram,
  value: ""
}

]);

and creating the input as:

{formFields.map((item, index) => {
      return (
        <div key={index}>
          <TextInput
            name={item.name}
            label={item.label}
            height={item.height}
            placeholder={item.placeholder}
            error={item.error}
            value={item.value}
            inputRef={register({
              required: true
            })}
            onChange={fieldOnChange(index)}
          />
          {item.error && <span>Enter a valide value</span>}
        </div>
      );
    })}

you can check the demo

any help please?

It's because you formFields in useState. It runs only one time. Show it already captures errors value ie first initially value. You need to either use useEffect to keep track change of error value or change condition of item.error to directly errors.

react-hook-form uses its errors for validation ie in your case it should be

{errors[item.name] && <span>Enter a valid value</span>}

Here is demo link : https://codesandbox.io/s/blue-shape-pv8jf

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