Open In App

How to validate checkbox form in angular 15

In Angular applications, it is often necessary to validate form inputs to ensure that users provide the required information correctly. Checkbox inputs are commonly used to allow users to select one or more options from a list. This article will cover different approaches to validating checkbox inputs in an Angular 17 form.

Prerequisites

Steps to validate the checkbox form in Angular

Step 1: Create an angular application

Once you have NodeJS and angular cli installed on your system, you can use the below commands to create your angular application.

ng new sample-app
cd sample-app

This will create an angular application named sample-app in the directory with and same name, then we can use the cd command to navigate to that directory.

Folder Structure:

Screenshot-2024-04-16-214902

Dependencies:

"dependencies": {
"@angular/animations": "^17.3.0",
"@angular/common": "^17.3.0",
"@angular/compiler": "^17.3.0",
"@angular/core": "^17.3.0",
"@angular/forms": "^17.3.0",
"@angular/platform-browser": "^17.3.0",
"@angular/platform-browser-dynamic": "^17.3.0",
"@angular/router": "^17.3.0",
"rxjs": "~7.8.0",
"tslib": "^2.3.0",
"zone.js": "~0.14.3"
}

Approach 1: using Template Driven forms

This approach focuses on html first approach, user can define all their validator in the html and by using the power of NgForm we can convert the html form into angular NgForm object. To start using it we must first import FormsModule in our app.component.ts.

<!-- app.component.html -->

<form #myForm="ngForm" (ngSubmit)="submit(myForm)">
    <label>
        <input type="checkbox" name="terms_and_cond" ngModel required>
        By checking this, I agree to your terms and conditions.
    </label>
    <br>
    <label>
        <input type="checkbox" name="news_letter" ngModel>
        Sign me up for the newsletter.
    </label>
    <br>
    <button type="submit" [disabled]="myForm.invalid">Submit</button>
</form>
/* app.component.scss */

form {
    width: 400px;
    border: 1px solid #ccc;
    border-radius: 8px;
    margin: 64px auto;

    display: flex;
    flex-direction: column;
    gap: 4px;

    padding: 16px;
    font-size: 16px;

    p,
    input {
        font-size: 20px;
    }

    button {
        height: 40px;
        font-size: 16px;
        border-radius: 20px;
    }
}
// app.component.ts

import { Component } from '@angular/core';
import { FormsModule, NgForm } from '@angular/forms';
import { RouterOutlet } from '@angular/router';

@Component({
    selector: 'app-root',
    standalone: true,
    imports: [RouterOutlet, FormsModule],
    templateUrl: './app.component.html',
    styleUrl: './app.component.scss'
})
export class AppComponent {
    title = 'sample-app';

    submit(ngForm: NgForm) {
        console.log(`valid: ${ngForm.form.valid}`);
        console.log(`value: `, ngForm.form.value);
    }
}

You can observe here that all the validators (here required) are defined in the html itself, while in our ts file we get the final NgForm object.

checkbox validation using template driven form

Output


This is a much simple approach to start with, but it has its limitation.

Approach 2: using Reactive Forms

This focuses on logic first approach, that is all the thing related to the form is defined in the ts file rather than the html file. For this to work we need to import the ReactiveFormsModule.

<!-- app.component.html -->

<form [formGroup]="myForm" (ngSubmit)="submit()">
    <label>
        <input type="checkbox" name="terms_and_cond" formControlName="terms_and_cond">
        By checking this, I agree to your terms and conditions.
    </label>
    <br>
    <label>
        <input type="checkbox" name="news_letter" formControlName="news_letter">
        Sign me up for the newsletter.
    </label>
    <br>
    <button type="submit" [disabled]="myForm.invalid">Submit</button>
</form>
/* app.component.scss */

form {
    width: 400px;
    border: 1px solid #ccc;
    border-radius: 8px;
    margin: 64px auto;

    display: flex;
    flex-direction: column;
    gap: 4px;

    padding: 16px;
    font-size: 16px;

    p,
    input {
        font-size: 20px;
    }

    button {
        height: 40px;
        font-size: 16px;
        border-radius: 20px;
    }
}
// app.component.ts

import { Component } from '@angular/core';
import { FormControl, FormGroup, ReactiveFormsModule, Validators } from '@angular/forms';
import { RouterOutlet } from '@angular/router';

@Component({
    selector: 'app-root',
    standalone: true,
    imports: [ReactiveFormsModule],
    templateUrl: './app.component.html',
    styleUrl: './app.component.scss',
})
export class AppComponent {
    title = 'sample-app';

    myForm = new FormGroup({
        terms_and_cond: new FormControl(false, [Validators.required]),
        news_letter: new FormControl(false),
    });

    submit() {
        console.log(`valid: ${this.myForm.valid}`);
        console.log(`value: `, this.myForm.value);
    }
}

You'll see that we're using something called a Validator here, which we import from the @angular/forms module. Angular comes with some handy pre-built validators for us to use, but we also have the option to create our own custom validators if we need something more specific.

Output for this code is same as that of the template driven approach.
Here is why you should use this approach.

Output:

checkbox validation using angular reactive form
Article Tags :