Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Form Validation in Angular

Form validation in Angular ensures that user inputs meet the required criteria before processing. This tutorial covers the basics of form validation and how to implement it effectively in your Angular applications.

What is Form Validation?

Form validation is the process of ensuring that form inputs are in the correct format and meet the specified requirements before they are submitted. Angular provides built-in validators as well as the ability to create custom validators.

Setting Up Form Validation

To use form validation, you need to import the necessary modules and set up your form controls with validators:

// 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({
      name: ['', [Validators.required, Validators.minLength(3)]],
      email: ['', [Validators.required, Validators.email]]
    });
  }

  onSubmit() {
    console.log('Form submitted!', this.userForm.value);
  }
}

// app.component.html
<form [formGroup]="userForm" (ngSubmit)="onSubmit()">
  <div>
    <label for="name">Name</label>
    <input type="text" id="name" formControlName="name">
    <div *ngIf="userForm.get('name').invalid && userForm.get('name').touched">
      <div *ngIf="userForm.get('name').errors.required">Name is required</div>
      <div *ngIf="userForm.get('name').errors.minlength">Name must be at least 3 characters long</div>
    </div>
  </div>
  <div>
    <label for="email">Email</label>
    <input type="email" id="email" formControlName="email">
    <div *ngIf="userForm.get('email').invalid && userForm.get('email').touched">
      <div *ngIf="userForm.get('email').errors.required">Email is required</div>
      <div *ngIf="userForm.get('email').errors.email">Invalid email format</div>
    </div>
  </div>
  <button type="submit" [disabled]="userForm.invalid">Submit</button>
</form>

Custom Validators

You can create custom validators for more complex validation logic:

// app.component.ts
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators, AbstractControl, ValidationErrors } 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({
      name: ['', [Validators.required, Validators.minLength(3)]],
      email: ['', [Validators.required, Validators.email]],
      password: ['', [Validators.required, this.passwordStrengthValidator]]
    });
  }

  passwordStrengthValidator(control: AbstractControl): ValidationErrors | null {
    const value = control.value;
    if (!value) {
      return null;
    }
    const hasUpperCase = /[A-Z]+/.test(value);
    const hasLowerCase = /[a-z]+/.test(value);
    const hasNumeric = /[0-9]+/.test(value);
    const passwordValid = hasUpperCase && hasLowerCase && hasNumeric;
    return !passwordValid ? { passwordStrength: true } : null;
  }

  onSubmit() {
    console.log('Form submitted!', this.userForm.value);
  }
}

// app.component.html
<form [formGroup]="userForm" (ngSubmit)="onSubmit()">
  <div>
    <label for="name">Name</label>
    <input type="text" id="name" formControlName="name">
    <div *ngIf="userForm.get('name').invalid && userForm.get('name').touched">
      <div *ngIf="userForm.get('name').errors.required">Name is required</div>
      <div *ngIf="userForm.get('name').errors.minlength">Name must be at least 3 characters long</div>
    </div>
  </div>
  <div>
    <label for="email">Email</label>
    <input type="email" id="email" formControlName="email">
    <div *ngIf="userForm.get('email').invalid && userForm.get('email').touched">
      <div *ngIf="userForm.get('email').errors.required">Email is required</div>
      <div *ngIf="userForm.get('email').errors.email">Invalid email format</div>
    </div>
  </div>
  <div>
    <label for="password">Password</label>
    <input type="password" id="password" formControlName="password">
    <div *ngIf="userForm.get('password').invalid && userForm.get('password').touched">
      <div *ngIf="userForm.get('password').errors.required">Password is required</div>
      <div *ngIf="userForm.get('password').errors.passwordStrength">Password must include upper case, lower case, and numeric characters</div>
    </div>
  </div>
  <button type="submit" [disabled]="userForm.invalid">Submit</button>
</form>

Displaying Validation Messages

Display validation messages conditionally based on the form control's state:

// app.component.html
<form [formGroup]="userForm" (ngSubmit)="onSubmit()">
  <div>
    <label for="name">Name</label>
    <input type="text" id="name" formControlName="name">
    <div *ngIf="userForm.get('name').invalid && userForm.get('name').touched">
      <div *ngIf="userForm.get('name').errors.required">Name is required</div>
      <div *ngIf="userForm.get('name').errors.minlength">Name must be at least 3 characters long</div>
    </div>
  </div>
  <div>
    <label for="email">Email</label>
    <input type="email" id="email" formControlName="email">
    <div *ngIf="userForm.get('email').invalid && userForm.get('email').touched">
      <div *ngIf="userForm.get('email').errors.required">Email is required</div>
      <div *ngIf="userForm.get('email').errors.email">Invalid email format</div>
    </div>
  </div>
  <div>
    <label for="password">Password</label>
    <input type="password" id="password" formControlName="password">
    <div *ngIf="userForm.get('password').invalid && userForm.get('password').touched">
      <div *ngIf="userForm.get('password').errors.required">Password is required</div>
      <div *ngIf="userForm.get('password').errors.passwordStrength">Password must include upper case, lower case, and numeric characters</div>
    </div>
  </div>
  <button type="submit" [disabled]="userForm.invalid">Submit</button>
</form>

Key Points

  • Form validation ensures user inputs meet the required criteria before processing.
  • Angular provides built-in validators such as required, minlength, maxlength, and email.
  • You can create custom validators for more complex validation logic.
  • Display validation messages conditionally based on the form control's state.

Conclusion

Form validation is a crucial aspect of building robust and user-friendly Angular applications. By leveraging Angular's built-in validators and creating custom validators when needed, you can ensure that your forms are both functional and secure. Happy coding!