Angular, Forms

Angular Template driven form Validation Example | Angular Form Validation | Email Validation | Phone Number Validation | Custom number only directive phone number Validation

Spread the love

Introduction for forms

In this article, we will learn about Template driven forms Validation by the Angular. We will create a simple user registration form and apply some validation built into it.

For full demo Template driven forms Validation provide Stackblitz and Github links. Please follow the tutorial and setup one by one as needed in your project.

We will consider the validation demo article below for that:

NgForm Required Validation

The <input> element carries the HTML validation attributes: required.

*app.component.html *

       <input
          name="mobileNumber"
          [ngModel]="user.mobileNumber"
          required
          #mobNumber="ngModel"
        />
        <div
          *ngIf="mobNumber.errors && userForm.submitted && !isValidFormSubmitted"
          [ngClass]="'error'"
>
          <div *ngIf="mobNumber.errors.required">
            Mobile number is required.
          </div>
        </div>

Phone Number Validation with Angular

Angular provides Pattern Validator directive that help validator to any control. We will use regex pattern as an attribute value.

app.component.html

<input
          name="mobileNumber"
          [ngModel]="user.mobileNumber"
          [pattern]="mobNumberPattern"
          required
          #mobNumber="ngModel"
        />
        <div
          *ngIf="mobNumber.errors && userForm.submitted && !isValidFormSubmitted"
          [ngClass]="'error'"
        >
          <div *ngIf="mobNumber.errors.required">
            Mobile number is required.
          </div>
          <div *ngIf="mobNumber.errors.pattern">
            Mobile number not valid.
          </div>
        </div>

app.component.ts

import { Component, VERSION } from '@angular/core';
import { NgForm } from '@angular/forms';
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
 mobNumberPattern = "^((\\+91-?)|0)?[0-9]{10}$"; 
 
 isValidFormSubmitted = false;  
 user = new User();  

 onFormSubmit(form: NgForm) {  
   this.isValidFormSubmitted = false;  
   if (form.invalid) {  
      return;  
   }  
   this.isValidFormSubmitted = true;  
   form.resetForm();  
 }  
}  

export class User {  
 mobileNumber ?: string;

}  

Email Validation with Angular

We will use here regex pattern to confirm email id. Pattern attribute will use with input tag.

app.component.html

        <input
          name="email"
          [ngModel]="user.email"
          [pattern]="emailPattern"
          #email="ngModel"
          required
        />
        <div
          *ngIf="email.errors && userForm.submitted && !isValidFormSubmitted"
          [ngClass]="'error'"
        >
          <div *ngIf="email.errors.required">
            Email is required.
          </div>
          <div *ngIf="email.errors.pattern">
            Email is not valid.
          </div>
        </div>

For email pattern variable use here emailPattern.

app.component.ts

export class AppComponent  {
 mobNumberPattern = "^((\\+91-?)|0)?[0-9]{10}$"; 
 emailPattern = "[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$"; 
 isValidFormSubmitted = false;  
 user = new User();  


 onFormSubmit(form: NgForm) {  
   this.isValidFormSubmitted = false;  
   if (form.invalid) {  
      return;  
   }  
   this.isValidFormSubmitted = true;  
   form.resetForm();  
 }  
}  

export class User {  
 mobileNumber ?: string; 
 email ?:string; 
}

Output:

Validation in template driven forms

Number only directive Validation

We will learn how to create custom directive for Number only input validation. Follow the step below to add onlyNumber directive to avoid entry except number.

add a new file only-number.directive.ts

import { Directive, ElementRef, forwardRef, HostListener, Renderer2, StaticProvider } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';

export const CUSTOM_INPUT_DATE_PICKER_CONTROL_VALUE_ACCESSOR: StaticProvider = {
    provide: NG_VALUE_ACCESSOR,
    useExisting: forwardRef(() => OnlyNumberDirective),
    multi: true
};

@Directive({
    selector: '[onlyNumber]',
    providers: [CUSTOM_INPUT_DATE_PICKER_CONTROL_VALUE_ACCESSOR]
})
export class OnlyNumberDirective implements ControlValueAccessor {
    private onChange: (val: string) => void;
    private onTouched: () => void;
    private value: string;

    constructor(
        private elementRef: ElementRef,
        private renderer: Renderer2
    ) {
    }

    @HostListener('input', ['$event.target.value'])
    onInputChange(value: string) {
        const filteredValue: string = filterValue(value);
        this.updateTextInput(filteredValue, this.value !== filteredValue);
    }

    @HostListener('blur')
    onBlur() {
        this.onTouched();
    }

    private updateTextInput(value: string, propagateChange: boolean) {
        this.renderer.setProperty(this.elementRef.nativeElement, 'value', value);
        if (propagateChange) {
            this.onChange(value);
        }
        this.value = value;
    }

    // ControlValueAccessor Interface
    registerOnChange(fn: any): void {
        this.onChange = fn;
    }

    registerOnTouched(fn: any): void {
        this.onTouched = fn;
    }

    setDisabledState(isDisabled: boolean): void {
        this.renderer.setProperty(this.elementRef.nativeElement, 'disabled', isDisabled);
    }

    writeValue(value: any): void {
        value = value ? String(value) : '';
        this.updateTextInput(value, false);
    }
}

function filterValue(value): string {
    return value.replace(/[^0-9]*/g, '');
}

import the directive to AppModule

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

import { AppComponent } from './app.component';
import { HelloComponent } from './hello.component';
import { OnlyNumberDirective } from './only-number.directive';

@NgModule({
  imports:      [ BrowserModule, FormsModule ],
  declarations: [ AppComponent, HelloComponent, OnlyNumberDirective ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

add onlyNumber custom directive in input tag element

app.component.html

<input
          name="mobileNumber"
          onlyNumber
          [ngModel]="user.mobileNumber"
          [pattern]="mobNumberPattern"
          required
          #mobNumber="ngModel"
        />

Conclusion

That’s it. In this tutorial we have learned validation of email, mobile number with 10 digits. using Pattern Validator and number only directive. If you have any doubt on Template Driven Form Validation please comment.

Thank you for reading. Please subscribe my blog to get latest updates!

Love this Angular template driven forms tutorial?  Give my repo a star.
Star


Spread the love
Tagged , , , , ,

About Chandra

Technology lover. Professionally Software Developer and write some Technical Blog to help newcomer.
View all posts by Chandra →

1 thought on “Angular Template driven form Validation Example | Angular Form Validation | Email Validation | Phone Number Validation | Custom number only directive phone number Validation

Leave a Reply

Your email address will not be published.