Custom Validators in Angular 6


Create new folder named learnangular5withrealapps and select to this folder in Visual Studio Code

Open Terminal windows in Visual Studio Code and type: npm install -g @angular/cli to install Angular 6




Create new folder, named validators in src\app folder. In this folder, create custom validators as below:

Create new TypeScript file, named max.validator.ts in src\app\validators folder

import { AbstractControl, ValidatorFn } from '@angular/forms';

export function max(value: Number): ValidatorFn {
    return (control: AbstractControl): { [key: string]: any } => {
        const input = control.value, isValid = input > value;
        if (isValid) {
            return { 'max': { value } }
        }
        else {
            return null;
        }
    };
}

Create new TypeScript file, named min.validator.ts in src\app\validators folder

import { AbstractControl, ValidatorFn } from '@angular/forms';

export function min(value: Number): ValidatorFn {
    return (control: AbstractControl): { [key: string]: any } => {
        const input = control.value, isValid = input < value;
        if (isValid) {
            return { 'min': { value } }
        }
        else {
            return null;
        }
    };
}

Create new TypeScript file, named app.component.ts in src\app folder

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { max } from './validators/max.validator';
import { min } from './validators/min.validator';

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html'
})

export class AppComponent implements OnInit {

    registerForm: FormGroup;

    constructor(
        private formBuilder: FormBuilder
    ) { }

    ngOnInit() {
        this.registerForm = this.formBuilder.group({
            username: ['', [Validators.required, Validators.minLength(3), Validators.maxLength(10)]],
            password: ['', [Validators.required, Validators.pattern('^((?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{6,20})$')]],
            age: [0, [min(18), max(120)]],
            email: ['', [Validators.required, Validators.pattern(/\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/)]],
            website: ['', [Validators.pattern(/(https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,4}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*))/)]]
        });
    }

    save(): void {
        console.log('Account Info');
        console.log('Username: ' + this.registerForm.value.username);
        console.log('Password: ' + this.registerForm.value.password);
        console.log('Age: ' + this.registerForm.value.age);
        console.log('Email: ' + this.registerForm.value.email);
        console.log('Website: ' + this.registerForm.value.website);
    }

}




Create new file, named app.component.html in src\app folder.

<h3>Register Form</h3>
<form [formGroup]="registerForm" (ngSubmit)="save()">
    <table>
        <tr>
            <td>Username</td>
            <td>
                <input type="text" formControlName="username">
            </td>
            <td>
                <div *ngIf="registerForm.get('username').touched">
                    <div *ngIf="registerForm.hasError('required', ['username'])">
                        This field is required.
                    </div>
                    <div *ngIf="registerForm.hasError('minlength', ['username'])">
                        Please enter at least 3 characters.
                    </div>
                    <div *ngIf="registerForm.hasError('maxlength', ['username'])">
                        Please enter no more than 10 characters.
                    </div>
                </div>
            </td>
        </tr>
        <tr>
            <td>Password</td>
            <td>
                <input type="password" formControlName="password">
            </td>
            <td>
                <div *ngIf="registerForm.get('password').touched">
                    <div *ngIf="registerForm.hasError('required', ['password'])">
                        This field is required.
                    </div>
                    <div *ngIf="registerForm.hasError('pattern', ['password'])">
                        Your password does not meet complexity requirements.
                    </div>

                </div>
            </td>
        </tr>
        <tr>
            <td>Age</td>
            <td>
                <input type="number" formControlName="age">
            </td>
            <td>
                <div *ngIf="registerForm.get('age').touched">
                    <div *ngIf="registerForm.hasError('min', ['age'])">
                        Please enter a value greater than or equal to 18
                    </div>
                    <div *ngIf="registerForm.hasError('max', ['age'])">
                        Please enter a value less than or equal to 120
                    </div>
                </div>
            </td>
        </tr>
        <tr>
            <td>Email</td>
            <td>
                <input type="text" formControlName="email">
            </td>
            <td>
                <div *ngIf="registerForm.get('email').touched">
                    <div *ngIf="registerForm.hasError('required', ['email'])">
                        This field is required.
                    </div>
                    <div *ngIf="registerForm.hasError('pattern', ['email'])">
                        Please enter a valid email address.
                    </div>
                </div>
            </td>
        </tr>
        <tr>
            <td>Website</td>
            <td>
                <input type="text" formControlName="website">
            </td>
            <td>
                <div *ngIf="registerForm.get('website').touched">
                    <div *ngIf="registerForm.hasError('pattern', ['website'])">
                        Please enter a valid URL.
                    </div>
                </div>
            </td>
        </tr>
        <tr>
            <td>&nbsp;</td>
            <td>
                <input type="submit" value="Save" [disabled]="registerForm.invalid">
            </td>
        </tr>
    </table>
</form>

In app.module.ts file in src\app folder. Add new component to module

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';

import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    ReactiveFormsModule
  ],
  providers: [
  ],
  bootstrap: [AppComponent]
})

export class AppModule { }

In Terminal windows in Visual Studio Code and type: ng serve --open, program will open url http://localhost:4200/ on browser




I recommend you refer to the books below to learn more about the knowledge in this article: