Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Conditional Validation in Angular

Conditional validation in Angular allows you to apply validation rules based on the value of other form controls or specific conditions. This tutorial covers the basics of implementing conditional validation effectively in your Angular forms.

Setting Up Conditional Validation

To set up conditional validation, you need to create a reactive form and define validation rules that change based on the value of other form controls:

// app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { ReactiveFormsModule } from '@angular/forms';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule, ReactiveFormsModule],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

// app.component.ts
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  userForm: FormGroup;

  constructor(private fb: FormBuilder) {
    this.userForm = this.fb.group({
      subscribe: [false],
      email: [''],
      phone: ['']
    });

    this.userForm.get('subscribe').valueChanges.subscribe(value => {
      const emailControl = this.userForm.get('email');
      if (value) {
        emailControl.setValidators([Validators.required, Validators.email]);
      } else {
        emailControl.clearValidators();
      }
      emailControl.updateValueAndValidity();
    });
  }

  onSubmit() {
    if (this.userForm.valid) {
      console.log('Form submitted!', this.userForm.value);
      // Handle form submission logic here
    } else {
      console.log('Form is invalid');
    }
  }
}

// app.component.html
Email is required
Invalid email format

Key Points

  • Conditional validation allows you to apply validation rules based on specific conditions or the value of other form controls.
  • Use the valueChanges observable to react to changes in form control values and update validation rules accordingly.
  • Use setValidators and clearValidators methods to dynamically apply or remove validators.
  • Call updateValueAndValidity to ensure the form control's state is updated after changing validators.

Conclusion

Conditional validation in Angular provides a flexible way to apply validation rules based on specific conditions. By understanding and implementing conditional validation effectively, you can create robust and user-friendly forms in your Angular applications. Happy coding!