Angular: Using Bootstrap Form Validation in Angular

Abhishek Wadalkar
3 min readOct 7, 2024

--

Angular provides a robust form validation system, and when combined with Bootstrap’s styling, creates an intuitive user experience. Below is a comprehensive guide on implementing Bootstrap form validation in an Angular application.

Prerequisites

  • Angular CLI installed
  • Bootstrap installed in your Angular project
  • Basic understanding of Angular forms and Bootstrap CSS.

Form Validation Example

The provided code snippet demonstrates how to integrate Bootstrap form validation with Angular reactive forms.

Before Validation
<!-- app-user-form.component.html -->
<form [formGroup]="userForm" (ngSubmit)="addUser()" class="needs-validation">
<!-- First Name -->
<div class="mb-3">
<label for="firstname" class="form-label">First Name</label>
<input
type="text"
class="form-control"
id="validationCustom01"
placeholder="First Name"
name="firstname"
formControlName="firstname"
[class.is-invalid]="userForm.controls?.['firstname'].invalid && userForm.controls?.['firstname'].touched"
required
/>
<div
class="invalid-feedback"
*ngIf="userForm.controls?.['firstname'].invalid && userForm.controls?.['firstname'].touched"
>
Please Enter FirstName
</div>
</div>

<!-- LastName -->
<div class="mb-3">
<label for="lastname" class="form-label">LastName</label>
<input
type="text"
class="form-control"
id="lastname"
placeholder="LastName"
name="lastname"
formControlName="lastname"
[class.is-invalid]="userForm.controls?.['lastname'].invalid && userForm.controls?.['lastname'].touched"
required
/>
<div
class="invalid-feedback"
*ngIf="userForm.controls?.['lastname'].invalid && userForm.controls?.['lastname'].touched"
>
Please Enter LastName
</div>
</div>

<!-- Email -->
<div class="mb-3">
<label for="email" class="form-label">Email</label>
<input
type="email"
class="form-control"
id="email"
placeholder="Email"
name="email"
formControlName="email"
[class.is-invalid]="userForm.controls?.['email'].invalid && userForm.controls?.['email'].touched"
required
/>
<div
class="invalid-feedback"
*ngIf="userForm.controls?.['email'].invalid && userForm.controls?.['email'].touched"
>
<ng-container *ngIf="userForm.controls?.['email'].errors?.['required']; else pattern">
Please Enter Email
</ng-container>
<ng-template #pattern> Please Enter Valid Email </ng-template>
</div>
</div>

<!-- Address -->
<div class="mb-3">
<label for="address" class="form-label">Address</label>
<textarea
class="form-control"
id="address"
rows="3"
placeholder="Enter Address"
name="address"
formControlName="address"
required
[class.is-invalid]="userForm.controls?.['address'].invalid && userForm.controls?.['address'].touched"
></textarea>
<div
class="invalid-feedback"
*ngIf="userForm.controls?.['address'].invalid && userForm.controls?.['address'].touched"
>
Please Enter Address
</div>
</div>

<button type="submit" class="btn btn-primary">
{{ isEdit ? "Update User" : "Add User" }}
</button>
<button type="button" class="btn btn-primary ms-3" (click)="onClear()">
Clear
</button>
</form>
<!-- app-user-form.component.ts -->
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';

@Component({
selector: 'app-user-form',
templateUrl: './user-form.component.html',
styleUrls: ['./user-form.component.css'],
standalone: true,
})
export class UserFormComponent implements OnInit {
userForm: FormGroup;
isEdit = false;

ngOnInit(): void {
this.userForm = new FormGroup({
firstname: new FormControl('', [Validators.required]),
lastname: new FormControl('', [Validators.required]),
email: new FormControl('', [Validators.required, Validators.email]),
address: new FormControl('', [Validators.required])
});
}

addUser() {
if (this.userForm.valid) {
console.log(this.userForm.value);
// API call to add user
}
}

onClear() {
this.userForm.reset();
}
}
Input Validation Error Messages on Add User Button Click with Empty Fields

Explanation

The form uses Angular’s reactive forms to create a FormGroup instance (userForm) that contains four FormControl instances: firstname, lastname, email, and address. Each FormControl has the following properties:

  • Validators.required: Ensures the field is not empty.
  • Validators.email (for email field): Validates the input as an email address.

Key Features

  • Validation: The form fields are validated using Angular’s built-in validators. Additional custom validators can be created and added as needed.
  • Bootstrap Classes: Bootstrap classes (form-control, is-invalid, invalid-feedback) are used to style the form fields and display validation messages.
  • ngIf Directives: The *ngIf directive is used to conditionally display validation messages based on the field's validity and touch status.
  • FormGroup and FormControl: The FormGroup and FormControl instances provide access to the form data and validation status.

How it Works

  • The user interacts with the form, entering data and triggering validation checks.
  • Angular updates the FormControl instances' validity status based on the input data.
  • The *ngIf directives evaluate the FormControl instances' validity and touch status, displaying or hiding validation messages accordingly.
  • When the form is submitted, the addUser() method checks the userForm validity. If valid, it proceeds with the API call to add the user.

Best Practices

  • Use Angular’s reactive forms for complex form handling and validation.
  • Leverage Bootstrap’s CSS classes for consistent and responsive form styling.
  • Utilize *ngIf directives for conditional rendering of validation messages.
  • Keep form logic separate from component logic using services or separate form components.

Common Issues and Solutions

  • Validation not working: Verify that the FormControl instances are properly linked to the HTML form fields.
  • Validation messages not displaying: Check that the *ngIf directives are correctly evaluating the FormControl instances' validity and touch status.
  • Form submission not triggering: Ensure that the ngSubmit event is properly bound to the form submission handler.

By following this guide, you can effectively integrate Bootstrap form validation with Angular reactive forms, creating a seamless and intuitive user experience.

--

--

Abhishek Wadalkar
Abhishek Wadalkar

Written by Abhishek Wadalkar

Passionate Frontend developer with 4 years experience, crafting seamless, user-centric web experiences. Exploring the world of web development and constantly.

No responses yet