Angular – Reactive Forms Validation

angular

Deprecated: get_the_author_email is deprecated since version 2.8.0! Use get_the_author_meta('email') instead. in /home/cloudber/public_html/wp-includes/functions.php on line 4713

This article shows how to create a Reactive Angular form with email validation.

1. Add required Angular modules into app.module

Import ReactiveFormsModule & BrowserModule in app.module.ts

app/app.module.ts
import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { ReactiveFormsModule } from '@angular/forms';

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

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

2. Create Form Group in component

Import FormGroup, Validators and FormControl classes in the component i.e app.component.ts for our page in order to explicitly define our control objects.

Create an instance of the FormGroup class and specify all the fields in our form. To put it simply, we will list key-value pairs. The keys will be the names of the fields and the values will be the form objects.


this.sampleform = new FormGroup({
email: new FormControl("", [Validators.minLength(3), Validators.maxLength(20), Validators.required, Validators.pattern('[^@]+@[^@]+\.[a-zA-Z]{2,6}')])});
}

Use the minLength, maxLength, required and pattern validators from the Validators class for the field for validation.

app/app.component.ts
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
@Component({
  selector: 'cloudberry-app',
  templateUrl: './src/app/app.component.html',
  styleUrls: ['./src/app/app.component.css']
})
export class AppComponent implements OnInit{ 
    
    private sampleForm : FormGroup;
    
    ngOnInit() {
      this.sampleform = new FormGroup({ 
        email: new FormControl("", [Validators.minLength(3), Validators.maxLength(20), Validators.required, Validators.pattern('[^@]+@[^@]+\.[a-zA-Z]{2,6}')])});
    }
    
    get email(){
      return this.sampleform.get("email");
    }
}

3. Create a HTML input element

Create a new HTML form tag with formGroup directive.

<form [formGroup]="sampleForm"></form>

Then create an input field of email type. Apply formControlName directive, and set is value to the corresponding key in the list of FormGroup.

app/app.component.html (Part 1)
<form [formGroup]="sampleform">
      <div class="form-group">
        <label for="email">Email address</label>
        <input formControlName="email" type="email" class="form-control" id="email" aria-describedby="emailHelp" placeholder="Enter email">
         <div class="alert alert-danger" role="alert" *ngIf="email.touched && email.errors">
            <div *ngIf="email.errors.minlength">Email cannot be less than 3 characters</div>
            <div *ngIf="email.errors.required">Email is required</div>
            <div *ngIf="email.errors.maxlength">Email cannot be more than 20 characters</div>
            <div *ngIf="email.errors.pattern">Email must be an email pattern</div>
        </div>
        <small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
      </div>
    </form>

4. Create Bootstrap Alert Message Box

Now, create alert messages for specific errors.

For example, if user enters invalid number of characters, then display a specific error message to indicate that the characters should not exceed or less than a number of characters.

app/app.component.html (Part 2)
<div class="alert alert-danger" role="alert" *ngIf="email.touched && !email.valid">
    <div *ngIf="email.errors.minlength">Email cannot be less than 3 characters</div>
    <div *ngIf="email.errors.required">Email is required</div>
    <div *ngIf="email.errors.maxlength">Email cannot be more than 20 characters</div>
    <div *ngIf="email.errors.pattern">Email must be an email pattern</div>
</div>

The trick to display correspond message to a specific error is to use *ngIf, with condition.

4. Create style for input elements

Angular automatically add a class i.e .ng-invalid into the element which has error. Therefore, in order to highlight the input element by showing red color in the text-box’s border, create a style of .ng-invalid. Example can be found in app.component.css

Author: Wu Chia Chong

My main areas of interest are software architectures and software design methods, patterns, and new trends in software development.

Author: Wu Chia Chong

My main areas of interest are software architectures and software design methods, patterns, and new trends in software development.