web-profile

Angular form conditional validation

html:

<h2>Form with conditional validation</h2>

<form [formGroup]="myForm" novalidate>
  <div>
    Make email mandatory
    <input formControlName="checkboxField" type="checkbox" />
  </div>
  <div>Email: <input formControlName="emailField" type="email" /></div>
  <button (click)="onSubmit()" [disabled]="myForm.invalid">Submit</button>
</form>

<h2>Debug</h2>

<h4>Is form valid? {{ myForm.valid }}</h4>

emailField errors:
<pre>{{ myForm.controls?.emailField?.errors | json }}</pre>

js:

import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
})
export class AppComponent implements OnInit {
  myForm: FormGroup;
  constructor() {}

  private emailValidators = [
    Validators.maxLength(250),
    Validators.minLength(5),
    Validators.pattern('^[a-zA-Z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,8}$'),
  ];

  ngOnInit() {
    this.myForm = new FormGroup({
      checkboxField: new FormControl(''),
      emailField: new FormControl('', this.emailValidators),
    });

    this.myForm.get('checkboxField').valueChanges.subscribe((inputValue) => {
      if (inputValue) {
        this.myForm.controls['emailField'].setValidators(
          this.emailValidators.concat(Validators.required)
        );
      } else {
        this.myForm.controls['emailField'].setValidators(this.emailValidators);
      }
      this.myForm.controls['emailField'].updateValueAndValidity();
    });
  }

  onSubmit() {
    console.log(this.myForm.value);
  }
}

Leave a Reply

Your email address will not be published.