Angular 6 Form Validation Example Tutorial

Angular 6 Form Validation Example Tutorial is the topic, we will discuss today. Angular is the platform that makes it easy to build applications within the web. Angular combines the declarative templatesdependency injection, an end to end tooling, and integrated best practices to solve development challenges. User actions such as clicking a linkpushing a button, and entering text raise the DOM events. Angular Forms are the main focus of any business applications. We can improve the overall data quality by validating user input for accuracy and completeness.

Angular 6 Form Validation Example Tutorial

First, we will install Angular 6 using Angular CLI, and then we start validating the Form Fields.

#1: Install Angular 6 using Angular CLI

Install Angular globally by the following command.

npm install -g @angular/cli

Now, we can create a new Angular 6 project using the following command.

ng new angular-validation

 

Angular 6 Form Validation Example Tutorial

Now, go inside the project and start the Angular Development Server.

cd angular-validation && ng serve --open

#2: Import ReactiveFormsModule

Let us talk about two types of forms in Angular.

  1. Reactive Forms
  2. Template Driven Forms

#Angular Reactive Forms

Angular Reactive Forms is also known as model-driven forms. Angular Reactive Forms offer an easy way to use reactive patterns and validations. Angular reactive forms follow the reactive programming style that supports the explicit data management flow between non-UI data models and a UI-oriented form model that keeps tracking the states and values of HTML controls on the screen.

When coding the reactive forms, we will avoid the directives required, ngModel, NgForm and such. The idea is that we use the underlying APIs to do it for us. In a sense, instead of binding Object models to directives like it happens in template-driven forms, we create our instances inside the component class and build our very own JS models. The main benefit of this approach has a lot more power and is remarkably productive to work with since it allows us to write robust code instead of dividing it into different form templates.

With the help of Reactive Forms, you will be able to create and manipulate the form control objects directly inside Component. Since the component class has access to a form control structure and a data model, you can push the data model values into the form controls as well as pull out the values that have been changed by a user. A component can observe changes in a form control state and react to them. It is especially useful for showing a validation message.

#Angular Template-driven forms

Template-driven forms have a separate approach. You can place the HTML form controls (such as <input> or <select>) inside the component template and bind them to the data model properties, using directives like ngModelWith the help of template-driven forms, you don’t need to create Angular form control objects. They are created by the Angular directives using the information from your data bindings. You don’t have to push and pull data values around because of Angular handles that for you through the ngModel directive.

For this example, we will use the Angular Reactive Forms Module. Import the module inside the app.module.ts file.

// app.module.ts

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

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

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

Okay, now we will create one form, but before that, we need to include the Bootstrap 4. So let us install it using the following command.

npm install bootstrap --save

Now, include the bootstrap css file inside the angular.json file.

"styles": [
    "src/styles.css",
    "node_modules/bootstrap/dist/css/bootstrap.min.css"
 ],

#3: Add FormFields and Validation.

We will take two fields to validate the Angular Forms. First, we need to add the following code inside the app.component.ts file.

// app.component.ts

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';
  angForm: FormGroup;
   constructor(private fb: FormBuilder) {
    this.createForm();
  }
   createForm() {
    this.angForm = this.fb.group({
      name: ['', Validators.required],
      price: ['', Validators.required]
    });
  }
}

Here, we have imported the FormGroup, FormBuilder and Validators modules from @angular/forms.

FormGroup tracks a value and the validity state of the FormBuilder instance group. It aggregates the values of each child FormControl into one object, using the name of each form control as the key. It calculates its status by reducing the ranks of its children. If one of the controls inside the group is invalid, an entire group becomes invalid, and if we have written the logic on the submit button to disable, then it will disable until all the errors are resolved. So user can’t send the form while there is still an error in one field.

FormBuilder is the helper class that creates FormGroupFormControl and FormArray instances for us. It radically reduces the repetition and clutter by handling details of form control creation for you. All of the modules should be imported from the @angular/forms module.

Okay, now write the following code inside the app.component.html file.

<div class="container">
  <h2>Angular 6 Validation</h2>
  <form [formGroup]="angForm" novalidate>
    <div class="form-group">
      <label class="center-block">Stock Name: </label>
      <input class="form-control" formControlName="name">
    </div>
    <div *ngIf="angForm.controls['name'].invalid && (angForm.controls['name'].dirty || angForm.controls['name'].touched)" class="alert alert-danger">
        <div *ngIf="angForm.controls['name'].errors.required">
          Name is required.
        </div>
      </div>
    <div class="form-group">
      <label class="center-block">Stock Price: </label>
      <input class="form-control" formControlName="price">
    </div>
    <div *ngIf="angForm.controls['price'].invalid && (angForm.controls['price'].dirty || angForm.controls['price'].touched)" class="alert alert-danger">
        <div *ngIf="angForm.controls['price'].errors.required">
          Price is required.
        </div>
      </div>
    <div class="form-group">
        <button class="btn btn-primary" color="primary" mat-raised-button type="submit" [disabled]="angForm.pristine || angForm.invalid">Submit</button>
    </div>
  </form>
</div>

Save the file and go to the http://localhost:4200.

Angular Reactive Form Validation

 

User experience is the essential thing while we develop any web application. We need to avoid interrupting and annoying the user because when the user submits the form, we will display all the errors then.  Imagine the scenario, where the user spent time filling each input and finally when he thinks a task is done; multiple errors throws at his screen that shows the invalid data. This is frustrating. Instead, we should consider the Real-time validation: It means validating the user input as you type. These validations are super handy and user-friendly. The great thing is that it the default for Angular Validators.

Finally, Angular 6 Form Validation Example Tutorial is over.

Add a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.