0% found this document useful (0 votes)
29 views

Topic 15 Forms and Validation

Angular forms allow handling user input and validation. There are template-driven and reactive forms. Template-driven forms use directives and are simpler, while reactive forms are more programmatic and flexible. Form validation ensures user input meets criteria using built-in and custom validators.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views

Topic 15 Forms and Validation

Angular forms allow handling user input and validation. There are template-driven and reactive forms. Template-driven forms use directives and are simpler, while reactive forms are more programmatic and flexible. Form validation ensures user input meets criteria using built-in and custom validators.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 25

Forms and validation

Angular forms
Angular Forms are a crucial part of building dynamic and interactive user interfaces in Angular
applications.

They allow you to handle user input, validation, and form submission seamlessly.
Types of Angular Forms

1. Template-Driven Forms
Directives:

1. ngForm: Used to create a form


Template-driven forms are the simpler and more declarative instance.
approach to handling forms in Angular. 2. ngModel: Enables two-way data
binding for form controls.
3. ngModelGroup: Groups form
controls and tracks their validity.
They rely on directives in the HTML template to create and 4. ngSubmit: Handles the form
manage the form submission event.
Key points
Advantages:
Directives:
● Quick and easy to set up, especially for simple
1. ngForm: Used to create a form
forms.
instance. ● Less boilerplate code in the component.
2. ngModel: Enables two-way data
binding for form controls.
3. ngModelGroup: Groups form Limitations:
controls and tracks their validity.
4. ngSubmit: Handles the form ● Limited flexibility for complex forms.
submission event. ● Testing can be challenging.
Example
<form #myForm="ngForm"
(ngSubmit)="onSubmit()">
<input type="text" name="username"
ngModel required>
<input type="password" name="password"
ngModel required>
<button type="submit" [disabled]="!
myForm.valid">Submit</button>
</form>
Types of Angular Forms

2. Reactive Forms

Reactive forms are a more programmatic and flexible approach to handling forms.

They are created and managed programmatically in the component class


Key points
Classes:
Advantages:
● FormGroup: Represents a group
of controls. ● Dynamic and highly customizable, suitable for
● FormControl: Represents a single complex forms.
form control. ● Easier to unit test.
● FormArray: Represents an array of
form controls.
Limitations:

● More initial setup code compared to template-


Methods:
driven forms.
● FormBuilder: A utility class to
simplify the creation of form controls
and groups.
Example
import { Component, FormBuilder, FormGroup, Validators } from
'@angular/core';

@Component({
selector: 'app-my-form',
templateUrl: './my-form.component.html',
styleUrls: ['./my-form.component.css']
})
export class MyFormComponent {
myForm: FormGroup;

constructor(private fb: FormBuilder) {


this.myForm = this.fb.group({
username: ['', [Validators.required]],
password: ['', [Validators.required]]
});
}

onSubmit() {
// Form submission logic
}
}
Validation

In Angular, form validation is a crucial aspect of ensuring that user input meets certain criteria
or constraints before it is submitted to the server.

Angular provides both template-driven and reactive forms with built-in and custom validation
capabilities.
Built-in Validators
1. Required Validator

Its ensures that field is not empty

<input type="text" name="username" [(ngModel)]="user.username" required>


Built-in Validators
2. MinLength and MaxLength
Validators

Validates the minimum and maximum length of a string.

<input type="text" name="password" [(ngModel)]="user.password"


minlength="8" maxlength="20">
Built-in Validators

3. Pattern Validator

Validates the input against a regular expression pattern

<input type="text" name="email" [(ngModel)]="user.email" pattern="[a-zA-


Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}">
Built-in Validators

4.Email Validator

Checks if the input is a valid email address

<input type="email" name="email" [(ngModel)]="user.email">


Built-in Validators

5. Min and Max Validators

Validates numeric input against minimum and maximum values.

<input type="number" name="age" [(ngModel)]="user.age" min="18" max="99">


Custom Validators

Custom validators in Angular allow you to implement your own validation logic for form
controls.

These validators are functions that check if a given input is valid based on your specified
criteria.
Create Custom Validation

Step 1: import the necessary modules from @angular/forms:

import { AbstractControl, ValidatorFn, Validators } from


'@angular/forms';
Create Custom Validation
Define a function that returns a ValidatorFn. This function will
Step 2: perform the validation logic. It takes an AbstractControl as a
parameter and returns null if the validation passes, or an object with
validation errors if it fails.

export function customValidator(): ValidatorFn {


return (control: AbstractControl): { [key: string]:
any } | null => {
// Your validation logic here
// Example: Check if the input contains the word
"example"
const forbidden = /example/.test(control.value);

return forbidden ? { 'forbiddenValue': { value:


control.value } } : null;
};
}
Create Custom Validation
Apply the custom validator to the desired form control when
Step 3: building your form using the FormBuilder

import { Component } from '@angular/core';


import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { customValidator } from './validators';

@Component({
selector: 'app-my-form',
templateUrl: './my-form.component.html',
styleUrls: ['./my-form.component.css']
})
export class MyFormComponent {
myForm: FormGroup;

constructor(private fb: FormBuilder) {


this.myForm = this.fb.group({
username: ['', [Validators.required, customValidator()]],
// Other form controls...
});
}
}
Create Custom Validation

Step 4: Display Validation Errors in the Template

<div
*ngIf="myForm.get('username').hasError('forbiddenValu
e')">
Username cannot contain the word "example".
</div>
Remember
What module from @angular/forms is essential for working with forms in
Angular?

A) HttpClientModule
B) RouterModule
C) FormsModule
D) NgRxModule
C
Apply
How can you implement custom validation in Angular reactive forms?

A) By using ngModel directive


B) By extending the built-in Validators class
C) By configuring the @angular/forms module
D) By directly manipulating the DOM elements

B
Understand
What is the primary purpose of Angular validators?

A) Enhancing performance
B) Handling HTTP requests
C) Controlling form input quality
D) Styling user interfaces

C
Understand
In template-driven forms, how are validation error messages typically
displayed in the template?

A) Using Angular services


B) Through console.log
C) With *ngIf and form control properties
D) By creating a separate validation component
C
Thank You

You might also like