Laura
Laura

Reputation: 305

Is there some way to validate redux-form in a custom input?

I need to throw a validation error from my custom input component, and not let the user successfully submit the form. In this Codesandbox, I'm passing the maxLength prop to the Field with a custom input component RenderField. I want to validate the maxLength within the RenderField (see the comments in the Codesandbox).

Some observations:

Upvotes: 0

Views: 170

Answers (1)

anthropos
anthropos

Reputation: 11

Not sure if it will fit your needs but you can add your validation rules into onSubmit function which in your case is showResults

export default (async function showResults(values) {
  await sleep(500); // simulate server latency

  const { firstName } = values;

  if (firstName.length < 5)
    throw new SubmissionError({ firstName: "too short" });

  window.alert(`You submitted:\n\n${JSON.stringify(values, null, 2)}`);
});

then you can clean up the RenderField

const RenderField = ({
  input,
  placeholder,
  type,
  maxLength,
  meta: { error, dispatch, ...restMeta },
  ...rest
}) => {
  return (
    <div>
      <input
        {...input}
        placeholder={placeholder}
        type={type}
        style={{ border: 0, width: "100%" }}
      />
      <p>{error}</p>
    </div>
  );
};

Line below won't work because it is mutation, I don't see action creator which will be able to handle this properly.

if (errorMessage) error = errorMessage;

Also you can consider to track state of the button and show errors only if it was clicked.

But IMO the best solution would be really to handle validation in redux-form.

Upvotes: 1

Related Questions