ionic form validation code example

Example 1: ionic form example

// in component.ts
this.myForm = formBuilder.group({
    firstName: ['value'],
    lastName: ['value', *validation function goes here*],
    age: ['value', *validation function goes here*, *asynchronous validation function goes here*]
});

...

// in component.html
<form [formGroup]="myForm">
    <ion-input formControlName="firstName" type="text"></ion-input>
    <ion-input formControlName="lastName" type="text"></ion-input>
    <ion-input formControlName="age" type="number"></ion-input>
</form>

Example 2: ionic email validation

[Validators.required, Validators.pattern(/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/)]

Example 3: ng validation for ionic checkbox

export class RegisterComponent {

  registerForm: FormGroup;
  email = new FormControl('', [Validators.required]);
  password = new FormControl('', [Validators.required]);
  termsAndConditions = new FormControl(undefined, [Validators.required]);

  constructor(private formBuilder: FormBuilder) {
    this.registerForm = this.formBuilder.group({
      'email': this.email,
      'password': this.password,
      'termsAndConditions': this.termsAndConditions
    }, {validator: this.checkCheckbox });
  }
  public checkCheckbox(c: AbstractControl){
  if(c.get('termsAndConditions').value == false){
    return false;
  }else return true;
}
}