How to do form validation in Angular
Angular provides built-in form validation features that can be used to validate user input. There are two types of forms in Angular: template-driven forms and reactive forms. Here’s how to perform form validation in Angular using both types of forms:
*Template-driven Forms*
Template-driven forms use directives to add validation rules to the HTML elements in the form. For example, you can use the required
attribute to make a field required or the minlength
attribute to specify a minimum length for a field. Here's an example of how to create a template-driven form with validation:
<form #myForm="ngForm" (ngSubmit)="onSubmit()">
<label for="name">Name:</label>
<input type="text" id="name" name="name" ngModel required minlength="3">
<label for="email">Email:</label>
<input type="email" id="email" name="email" ngModel required>
<button type="submit">Submit</button>
</form>
In this example, required
and minlength
attributes are added to the name
input field, and the required
attribute to the email
input field. I have also added a submit button that calls anonSubmit()
method when clicked.
To display error messages when a field is invalid, you can use Angular's built-in error handling features. For example:
<div *ngIf="myForm.controls['name'].invalid && (myForm.controls['name'].dirty || myForm.controls['name'].touched)">
<div *ngIf="myForm.controls['name'].errors.required">
Name is required.
</div>
<div *ngIf="myForm.controls['name'].errors.minlength">
Name must be at least {{ myForm.controls['name'].errors.minlength.requiredLength }} characters long.
</div>
</div>
<div *ngIf="myForm.controls['email'].invalid && (myForm.controls['email'].dirty || myForm.controls['email'].touched)">
Email is required.
</div>
In this example, I have used Angular’s built-in *ngIf
directive to show error messages when a field is invalid. This will check if each field is invalid and has been touched or modified by the user before showing an error message.
*Reactive Forms*
Reactive forms are more flexible than template-driven forms and allow you to define your own custom validators. Here’s an example of how to create a reactive form with validation:
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
})
export class AppComponent {
myForm: FormGroup;
constructor(private fb: FormBuilder) {
this.myForm = this.fb.group({
name: ['', [Validators.required, Validators.minLength(3)]],
email: ['', [Validators.required]],
});
}
onSubmit() {
console.log(this.myForm.value);
}
}
In this example, I am using Angular’s built-in FormGroup
,FormControl
, andValidators
classes to define form fields and their validation rules. I have also used Angular's built-informBuilder
service to simplify creating our form.
To display error messages when a field is invalid, you can use similar code as in the template-driven form example above.