AppDividend
Latest Code Tutorials

Angular 7 Form Validation Example Tutorial

634

Get real time updates directly on you device, subscribe now.

Angular 7 Form Validation Example Tutorial is today’s leading topic.  In Angular, we have two kinds of forms, and those are Template Driven Form and Reactive Form. We will walk through the best practices to create the user-friendly forms and validations using Angular 7. After that, we will go through each Angular forms like template driven forms and reactive forms validations with the examples. We will see the fundamental concepts of Angular FormControl, FormGroup, FormBuilder, and different types of built-in validators.

Earn a Tech Degree and get the skills like Frontend Development or Javascript Development that can help you to launch a career. Check out this program

Angular 7 Form Validation Example Tutorial

Before we start Angular 7 Forms Validation Example, if you are new to Angular 7 Forms then check out this Angular 7 Forms Tutorial Example. Forms are almost always present in any website or web application or mobile app. Forms can be used to perform countless actions like data-entry tasks such as authentication, order submission or profile creation. Let’s keep in mind that the real objective of forms in web or mobile application is to get the data from the user. As it always happens in software development, there are so many different ways of sending and handling data in your server.

Template-driven Angular Form Validation

We can add the validation to the template-driven form; you add the same validation attributes as you would with native HTML form validation. Angular uses the directives to match these attributes with the validator functions in the system. Every time the value of the form control changes, Angular runs the validation and generates either the list of validation errors, which results in an INVALID status or null, which leads in the VALID status. Let us take an example, but first Install Angular 7.

#1: Install Angular 7

Type the following command to generate the new Angular project.

ng new ng7validation

 

Angular 7 Form Validation Example Tutorial

Now, go inside the ng7validation folder and create open the folder inside VSCode.

cd ng7validation
code .

Now, install the Bootstrap 4 CSS Framework using the following command.

npm install bootstrap --save

Now, include the bootstrap 4 inside the angular.json file inside styles array.

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

#2: Template Driven Angular 7 Form Validation.

Inside the app.module.ts file, we need to add the FormsModule.

// app.module.ts

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

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

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

Now, add the following code inside the app.component.ts file.

// app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  data: any = {};

  onSubmit() {
    alert(JSON.stringify(this.data));
  }
}

When the user submits the form, we will get here, and from here, we can send the data to the server.

Now, add the validation inside the template which is the app.component.ts file.

<div class="container">
  <h2>Angular Template Driven Form Validation</h2>
  <form name="form" (ngSubmit)="f.form.valid && onSubmit()" #f="ngForm" novalidate>
    <div class="form-group">
      <input id="name" name="name" class="form-control"
      required minlength="4" appForbiddenName="bob"
      [(ngModel)]="data.name" #name="ngModel"/>
    </div>
    <div class="form-group">
      <div *ngIf="name.invalid && (name.dirty || name.touched)"
          class="alert alert-danger">
        <div *ngIf="name.errors.required">
          Name is required.
        </div>
        <div *ngIf="name.errors.minlength">
          Name must be at least 4 characters long.
        </div>
        <div *ngIf="name.errors.forbiddenName">
          Name cannot be Bob.
        </div>
      </div>
    </div>
    <div class="form-group">
      <button class="btn btn-primary" [disabled]="f.form.pristine || f.form.invalid">Add Name</button>
    </div>
  </form>
</div>

Angular Template Driven Form Validation

If the validation errors are there, then the submit button is disabled, if the form status is valid then and then you can send the form with the values.

Want to learn to code, gain a new skill and get a new job. Check out this amazing program

#3: Angular 7 Reactive Form Validation Tutorial

We have seen the Angular 7 Template-driven form validation; now we will see the Angular 7 Reactive Form Validation.

Reactive Forms

Reactive forms is an Angular technique for creating forms in the reactive style. Angular reactive forms facilitate the reactive style of programming that favors an explicit management of the data flowing between a non-UI data model (typically retrieved from a server) and a UI-oriented form model that retains the states of the HTML form controls on the screen. Reactive Forms offer us the ease of using reactive programming patterns, testing, and validation. Let us take an example.

Related Posts
1 of 16

Now, import the ReactiveFormsModule inside the app.module.ts file.

// app.module.ts

import { ReactiveFormsModule } from '@angular/forms';

imports: [
    BrowserModule, ReactiveFormsModule
],

Now, we need to write the code for the app.component.ts file. Remember, this is not template-driven form. So we will change the code inside the app.component.ts file.

First, we import the FormGroup, FormBuilder, Validators modules from @angular/forms.

Also, create a constructor and instantiate the FormBuilder.

// 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 {
  angForm: FormGroup;
   constructor(private fb: FormBuilder) {
    this.createForm();
  }
   createForm() {
    this.angForm = this.fb.group({
       name: ['', Validators.required ]
    });
  }
}

We have used form builder to handle all the validation. So in that constructor, we are creating a form with the validation rules.

Now, write the following code inside an app.component.html file.

<div class="container">
  <h2>Angular Reactive Form Validation</h2>
  <form [formGroup]="angForm" novalidate>
      <div class="form-group">
        <label class="center-block">Name:
          <input class="form-control" formControlName="name">
        </label>
      </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>
</form>
<p>Form value: {{ angForm.value | json }}</p>
<p>Form status: {{ angForm.status | json }}</p>
</div>

Save the file and go to the browser and see the validation result with the values.

 

Angular Reactive Form Validation

Now, our complete form looks like below code with the submit button.

<div class="container">
  <h2>Angular Reactive Form Validation</h2>
  <form [formGroup]="angForm" novalidate>
      <div class="form-group">
        <label class="center-block">Name:
          <input class="form-control" formControlName="name">
        </label>
      </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">
        <button type="submit"
        [disabled]="angForm.pristine || angForm.invalid" class="btn btn-success">
        Save
      </button>
      </div>
</form>
<p>Form value: {{ angForm.value | json }}</p>
<p>Form status: {{ angForm.status | json }}</p>
</div>

Finally, Angular 7 Form Validation Example Tutorial is over. Thanks for taking.

Leave A Reply

Your email address will not be published.

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