Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 37 ยท Forms and Data

Ionic Form Validation: Reactive Forms and Error Messages

Validate Ionic forms: required, pattern and custom rules, Angular reactive forms, React and Vue approaches, showing errors at the right time and server errors.

A form that accepts anything is a bug factory, and a form that shouts errors at every keystroke is unpleasant to use. Good validation has three parts: rules (what is valid), timing (when to show a message) and feedback (how to show it). Ionic gives you the UI for feedback through helperText, errorText and the ion-invalid state; the rules come from your framework or plain functions. This lesson builds validation from pure functions up to complete forms.

Rules first: pure functions

Write rules as small functions that return an error string or null. They are easy to test and work in every framework.

JS Validation rules as pure functions

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Showing only the first error per field avoids a wall of red text.

Showing errors in Ionic

An ion-input shows errorText when it has the ion-invalid and ion-touched classes. Frameworks add those classes automatically (Angular forms does), or you set them yourself:

HTML
<ion-input
  label="Email"
  labelPlacement="floating"
  type="email"
  helperText="Use your work address"
  errorText="Enter a valid email address"
  class="ion-invalid ion-touched"
></ion-input>

The error shows only if both classes are present; helper text shows otherwise. That gives you "validate after the user has visited the field" behaviour for free in Angular. Elsewhere, track touched state yourself.

Timing: when to show an error

Strategy Behaviour Good for
On blur (touched) Error after leaving the field Most fields
On submit Errors after pressing the button Short forms
On input (live) Updates as you type Fixing an existing error, password strength

A good compromise: validate on blur the first time; once a field is invalid, re-validate on every keystroke so the message disappears as soon as the user fixes it. The next stand-in models this "reward early, punish late" rule.

JS Stand-in: when to show a field error

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Angular reactive forms

Reactive forms are the standard in Angular Ionic apps:

TypeScript
import { FormBuilder, Validators, ReactiveFormsModule } from '@angular/forms';

form = this.fb.nonNullable.group({
  email: ['', [Validators.required, Validators.email]],
  password: ['', [Validators.required, Validators.minLength(8)]],
});

constructor(private fb: FormBuilder) {}

submit() {
  if (this.form.invalid) { this.form.markAllAsTouched(); return; }
  console.log(this.form.getRawValue());
}
HTML
<form [formGroup]="form" (ngSubmit)="submit()">
  <ion-input label="Email" labelPlacement="floating" type="email" formControlName="email"
    errorText="Enter a valid email"></ion-input>
  <ion-input label="Password" labelPlacement="floating" type="password" formControlName="password"
    errorText="At least 8 characters"></ion-input>
  <ion-button type="submit" expand="block" [disabled]="form.invalid">Sign up</ion-button>
</form>

markAllAsTouched() reveals every error when the user presses submit on an untouched form. Custom validators are functions that return { key: true } or null, and cross-field rules (password match) go on the group.

React and Vue

React has no built-in forms library. Many Ionic React apps use React Hook Form with Controller because Ionic's inputs are custom elements:

JSX
<Controller
  name="email"
  control={control}
  rules={{ required: 'Email is required', pattern: { value: /^\S+@\S+\.\S+$/, message: 'Invalid email' } }}
  render={({ field, fieldState }) => (
    <IonInput
      label="Email"
      value={field.value}
      onIonInput={(e) => field.onChange(e.detail.value)}
      onIonBlur={field.onBlur}
      errorText={fieldState.error?.message}
      className={fieldState.error && fieldState.isTouched ? 'ion-invalid ion-touched' : ''}
    />
  )}
/>

In Vue, libraries such as VeeValidate or a handwritten computed errors object work well. The pure rule functions from the start of the lesson plug into any of them.

Submitting and server errors

Client checks improve usability; the server must validate again. Show server errors in the same place:

TypeScript
try {
  await api.signUp(values);
} catch (e) {
  if (e.status === 422) form.controls.email.setErrors({ server: e.errors.email[0] });
  else showToast('Something went wrong. Try again.');
}

While the request runs, disable the submit button or show ion-loading so users do not double submit. This block models a submit flow that guards against double taps:

JS Stand-in: guarded submit with server errors

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Accessibility and mobile polish

  • Associate every error with its field (Ionic does this with errorText).
  • Do not rely on red alone; the text carries the meaning.
  • Set the right autocomplete and inputmode.
  • Focus the first invalid field on submit failure.
  • Keep error text specific: "Password needs at least 8 characters" beats "Invalid".

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. When does ion-input show its errorText?

    Both classes are required; otherwise helperText shows.
  2. 2. Why validate again on the server?

    Client validation is a convenience, not protection.
  3. 3. What does markAllAsTouched do in Angular?

    Pressing submit on an untouched form should show every error.
  4. 4. Which is a good timing strategy?

    It avoids early nagging but gives quick feedback when fixing.

Summary

  • Write rules as pure functions returning a message or null.
  • Ionic shows errorText when ion-invalid and ion-touched are both set.
  • Validate on blur, then live while invalid; show one message per field.
  • Angular reactive forms, React Hook Form and VeeValidate integrate with Ionic inputs.
  • Always re-validate on the server and prevent double submits.

Next: Fetching Data and Pull to Refresh