Master Angular From Scratch

Learn Angular with clear, interactive, and structured lessons for beginners and developers.

ANGULAR COURSE SYLLABUS
1. Angular Introduction
Angular Introduction Angular History Angular Fundamentals Angular Architecture Component-Based Angular
2. Angular Setup
Angular Setup Introduction Installing Node.js Installing Angular CLI Creating an Angular Application Angular Project Structure
3. Components
Components Overview Component Anatomy Creating Components Component Selector Component Template Component Styles Component Metadata Standalone Components Parent and Child Components Reusable Components
4. Templates
Templates Introduction Template Syntax Template Expressions Template Statements Template Reference Variables ng-template ng-container ngTemplateOutlet Built-in Control Flow
5. Data Binding
Data Binding Introduction Interpolation Binding Property Binding Event Binding Two-Way Data Binding Class & Style Binding
6. Directives
Directives Introduction Attribute Directives Structural Directives Custom Directives
7. Pipes
Pipes Introduction Built-in Pipes Parameterized Pipes Chaining Pipes Custom Pipes
8. Event Handling
Event Handling Introduction DOM Events Event Binding Syntax Event Object Passing Data to Event Handlers
9. Input & Output
Component Communication @Input @Output EventEmitter
10. Lifecycle Hooks
Lifecycle Hooks Introduction ngOnInit ngOnChanges ngAfterViewInit ngOnDestroy
11. Services
Services Introduction Creating Angular Services Using Services in Components Sharing Data Through Services Service Scope
12. Dependency Injection
Dependency Injection Introduction Injecting Dependencies InjectionToken Provider Configuration
13. Routing
Routing Introduction Route Configuration RouterLink & Navigation Route Parameters Child Routes Route Guards
14. Forms
Angular Forms Introduction Template-Driven Forms Reactive Forms Form Validation Form Submission & Error Handling
15. HttpClient
HttpClient Introduction Configuring HttpClient GET Request POST, PUT & DELETE Requests Headers & Parameters HTTP Error Handling
16. Observables
Observables Introduction Creating & Subscribing to Observables Observable Data Streams Observable Operators Subscription Management
17. RxJS
RxJS Introduction RxJS Operators Transformation & Filtering Combining Observables Higher-Order Mapping Subjects
18. API Integration
API Integration Introduction Connecting Angular with REST API Consuming API Data CRUD API Integration API Response & Error Handling

Angular Form Validation

Learn how Angular validates user input using built-in validators, control states and validation messages in reactive and template-driven forms.

What is Form Validation?

Form validation checks whether the data entered by a user satisfies the rules required by the application.

For example, a course enquiry form may require a name, valid email address, mobile number and selected course.

Angular provides built-in validators and form states that make it easier to identify invalid input and show useful validation messages.

Form Validation Flow

User Input Enter Data
→
Validator Check Rules
→
Form State Valid / Invalid
→
Message Inform User

Main Validation Concepts

R
Required

Ensures that a required field is not empty.

E
Email

Checks whether an email value satisfies the validator.

M
Min / Max Length

Controls the allowed length of a field value.

S
Form State

Tracks valid, invalid, touched, dirty and related states.

Angular Validators

Angular provides built-in validators through the Validators class for reactive forms.

These validators can be combined to create validation rules for individual form controls.

Import Validators
import { FormControl, Validators }
    from '@angular/forms';

Validators.required

Validators.required checks that a control contains a value.

It is commonly used for fields such as name, course and mobile number.

Example
name = new FormControl(
    '',
    Validators.required
);

Validators.email

Validators.email applies Angular's email validation rule to a form control.

It can be combined with Validators.required when an email field must be provided and valid.

Example
email = new FormControl(
    '',
    [
        Validators.required,
        Validators.email
    ]
);

Validators.minLength

Validators.minLength checks that a control value has at least the specified number of characters.

Example
mobile = new FormControl(
    '',
    Validators.minLength(10)
);

Validators.maxLength

Validators.maxLength limits the maximum number of characters allowed in a control value.

Example
mobile = new FormControl(
    '',
    Validators.maxLength(10)
);

Using Multiple Validators

Multiple validators can be applied to the same form control by placing them inside an array.

This allows one field to satisfy more than one validation rule.

Example
email = new FormControl(
    '',
    [
        Validators.required,
        Validators.email,
        Validators.minLength(5)
    ]
);

Form Control States

V
Valid

The control satisfies its validation rules.

I
Invalid

One or more validation rules are not satisfied.

T
Touched

The user has interacted with the control.

D
Dirty

The user has changed the control value.

Validation Errors

Angular provides error information through the control's errors property.

This can be used to determine which validation rule has failed.

Example
const emailControl =
    this.registrationForm.get('email');

console.log(
    emailControl?.errors
);

Checking Required Error

Template
<div
    *ngIf="
        registrationForm.get('name')?.hasError('required')
        &&
        registrationForm.get('name')?.touched
    ">

    Name is required.

</div>

Checking Email Error

Template
<div
    *ngIf="
        registrationForm.get('email')?.hasError('email')
        &&
        registrationForm.get('email')?.touched
    ">

    Please enter a valid email address.

</div>

Checking Min Length Error

Template
<div
    *ngIf="
        registrationForm.get('mobile')?.hasError('minlength')
        &&
        registrationForm.get('mobile')?.touched
    ">

    Mobile number is too short.

</div>

CIIT Training Institute Validation Example

Suppose CIIT Training Institute has a course enquiry form with fields for name, email and mobile number.

Each field can have its own validation rules before the enquiry is submitted.

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

import {
    FormBuilder,
    Validators
} from '@angular/forms';

@Component({
    selector: 'app-enquiry',
    templateUrl: './enquiry.component.html'
})
export class EnquiryComponent {

    enquiryForm = this.fb.group({

        name: [
            '',
            Validators.required
        ],

        email: [
            '',
            [
                Validators.required,
                Validators.email
            ]
        ],

        mobile: [
            '',
            [
                Validators.required,
                Validators.minLength(10),
                Validators.maxLength(10)
            ]
        ],

        course: [
            '',
            Validators.required
        ]

    });


    constructor(
        private fb: FormBuilder
    ) {
    }

}
Template
<form [formGroup]="enquiryForm">


    <label>
        Name
    </label>

    <input
        type="text"
        formControlName="name">

    <div
        *ngIf="
            enquiryForm.get('name')?.invalid
            &&
            enquiryForm.get('name')?.touched
        ">

        Name is required.

    </div>


    <label>
        Email
    </label>

    <input
        type="email"
        formControlName="email">

    <div
        *ngIf="
            enquiryForm.get('email')?.hasError('required')
            &&
            enquiryForm.get('email')?.touched
        ">

        Email is required.

    </div>

    <div
        *ngIf="
            enquiryForm.get('email')?.hasError('email')
            &&
            enquiryForm.get('email')?.touched
        ">

        Enter a valid email address.

    </div>


    <label>
        Mobile
    </label>

    <input
        type="text"
        formControlName="mobile">

    <div
        *ngIf="
            enquiryForm.get('mobile')?.invalid
            &&
            enquiryForm.get('mobile')?.touched
        ">

        Enter a valid mobile number.

    </div>


    <button
        type="submit"
        [disabled]="enquiryForm.invalid">

        Submit Enquiry

    </button>

</form>

Validation Result

Name: Required

Email: Valid Email Required

Mobile: 10 Characters Required

Submit button: Disabled until form is valid

Validation in Template-driven Forms

Template-driven forms can use HTML validation attributes such as required, email, minlength and maxlength.

The control state can then be inspected through a template reference variable.

Example
<input
    type="email"
    name="email"
    ngModel
    required
    email
    #emailControl="ngModel">


<div
    *ngIf="
        emailControl.invalid
        &&
        emailControl.touched
    ">

    Please enter a valid email.

</div>

Checking Complete Form Validation

Reactive Form
if (this.enquiryForm.valid) {

    console.log(
        'Form is valid'
    );

}
else {

    console.log(
        'Form is invalid'
    );

}

Form Status

Angular evaluates the validation rules of the registered controls and exposes the overall form status through valid or invalid.

Marking Controls as Touched

When a user submits an incomplete form, it can be useful to mark controls as touched so that their validation messages become visible.

Example
submitForm() {

    if (this.enquiryForm.invalid) {

        this.enquiryForm.markAllAsTouched();

        return;

    }

    console.log(
        this.enquiryForm.value
    );

}

Common Validation Rules

Validator Purpose Example
required Ensures a value is provided. Validators.required
email Applies email validation. Validators.email
minLength Requires a minimum number of characters. Validators.minLength(10)
maxLength Limits the maximum number of characters. Validators.maxLength(10)
invalid Indicates that one or more rules are failing. form.invalid

Important Points

1. Validate Important Fields

Required information should be validated before the application processes the form.

2. Use Appropriate Validators

Select validators based on the actual requirements of each form field.

3. Show Useful Messages

Validation messages should clearly explain what the user needs to correct.

4. Validate Before Submission

Do not process form data until the form satisfies the required validation rules.

Form Validation Best Practices

  • Use appropriate validators for each field.
  • Display validation messages only when useful to the user.
  • Validate required fields before processing submitted data.
  • Use meaningful validation messages rather than generic errors.
  • Keep validation logic organized and easy to maintain.
  • Perform corresponding validation on the backend as well; client-side validation should not be treated as the only security or data-integrity check.

Summary

Angular Form Validation helps ensure that user-entered information satisfies the application's requirements.

Common reactive-form validators include Validators.required, Validators.email, Validators.minLength and Validators.maxLength.

Angular also tracks states such as valid, invalid, touched and dirty. In the next topic, we will learn about Form Submission.