How to show validation errors in Ionic 4 React

I’ve been looking everywhere and haven’t found how to go about showing different validation errors on form elements (eg IonInput). They have properties like maxLength required minLength etc. but (at least on web) they don’t work and plus they don’t show any errors (where to get the list of errors from anyways?). I could simulate the effect by getting the input value and run it through my own processing and use if else logic and create an error object but really? Do I have to do that myself? This would be pure boilerplate!

1 Like

I’m investigating the same question, with no joy. The example react app rolls its own validation, and if I’m reading the ionic core source correctly, there’s nothing react-specific being implemented for IonInput … the required field is just being carried over from a core JSX component. Sure would be nice if this were documented somewhere.

@mrlowe

manage forms and form validation in Ionic Framework / React Components

1 Like

I ended up using react-hook-form and I’m happy with it. Ionic 4 didn’t have support for property ref so I couldn’t use react-hook-forms out of the box and had to use register inside a useEffect Hook to attach the it to inputs like below:

  useEffect(() => {
    register(
      { name: "number" },
      {
        required: { value: true, message: "Number is required. " },
        minLength: { value: 5, message: "Minimum length is 5. " },
        pattern: { value: /^[0-9\b]+$/, message: "Number is wrong format. " }
      }
    );
  }, [register]);
              <IonInput
                name="number"
                type="tel"
                placeholder="Your number"
                spellCheck={false}
                inputmode="tel"
                autofocus={true}
                onIonChange={(e): void => {
                  setValue("number", e.detail.value);
                }}
                required
              />

However Ionic 5 seems to have added support for ref property so you probably can use it directly now (haven’t tested)

@sabahang You don’t want to use the ref property, see the blog post I attached on why you should be using controlled components. After I ran into issues, I spoke with the developer of react-hook-form and recommend that approach which is why I went that direction.

Once you get beyond simple input fields, it will just get problematic

1 Like

Thanks @aaronksaunders in your blog post you don’t really explain why using ref is not good and what issues you had with it? Have I missed it?