Form Validation 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 TypeScript file, named app.component.ts in src\app folder

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

@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})$')]],
            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('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>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: