Angular

Reactive Form With Validation In Angular 12

Introduction

In this article, we are going to learn Reactive Form with Validation in angular 12. We will create a simple registration form in that we will use inbuild validations.

The Reactive form provides a model driven approach to handle form inputs whose values change over time and Reactive forms are synchronous in nature.

Prerequisites:

  • Basic knowledge of Angular
  • Code editor like Visual Studio Code

Create a new Angular project by typing the following command in the VSCode terminal.

ng new ReactiveFormDemo

Now, open the newly created project and execute the command that’s given below. It will install ng-bootstrap for the default application.

ng add @ng-bootstrap/ng-bootstrap

Here, we are going to add Form Validation in our form.

Create a new component by using the following command.

ng g c reactive-form-demo

Open the app.module.ts file then add the ReactiveFormsModule in the file.

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

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { ReactiveformdemoComponent } from './reactive-form-demo/reactive-form-demo.component';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { ReactiveFormsModule, FormsModule } from '@angular/forms';

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

Open the reactive-form-demo.component.ts file and copy given code.

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
@Component({
  selector: 'app-reactive-form-demo',
  templateUrl: './reactive-form-demo.component.html',
  styleUrls: ['./reactive-form-demo.component.scss']
})
export class ReactiveformdemoComponent implements OnInit {
  userForm!: FormGroup;
  submitted = false;
  constructor(private fb: FormBuilder) { }
  
  ngOnInit(): void { 
    this.userForm = this.fb.group({
      txtName: ['', Validators.required],
      txtEmail: ['', [Validators.required, Validators.email]],
      txtMobile: ['', [Validators.required, Validators.minLength(10)]],
      txtPassword: ['', [Validators.required, Validators.minLength(6)]]
    });
  }
  get getform() {
    return this.userForm.controls;
  }

  onSubmit() {
    this.submitted = true;
    if (!this.userForm.valid) {
      return;

    }
    alert('SUCCESS' + JSON.stringify(this.userForm.value));
  }
  onReset() {
    this.submitted = false;
    this.userForm.reset();
}
}

Now, just open the reactive-form-demo.component.html copy given below code.

<div class="container">
    <div class="row">
        <div class="col-md-6 offset-md-3">
            <h3>Reactive Form With Validation</h3>
            <form [formGroup]="userForm" (ngSubmit)="onSubmit()" class="text-center border border-light p-5">
                <div class="form-group">

                    <input type="text" formControlName="txtName" placeholder="Name" class="form-control" [ngClass]="{ 'is-invalid': submitted && getform.txtName.errors }" />
                    <div *ngIf="submitted && (getform.txtName.errors || getform.txtName.touched)" class="text-danger">
                        <div *ngIf="getform.txtName.errors?.required">
                            First Name is required
                        </div>
                    </div>
                </div>
                <div class="form-group">

                    <input type="text" formControlName="txtMobile" class="form-control" placeholder="Mobile No" [ngClass]="{ 'is-invalid': submitted && getform.txtMobile.errors }" />
                    <div *ngIf="submitted && (getform.txtMobile.errors || getform.txtMobile.touched)" class="text-danger">
                        <div *ngIf="getform.txtMobile.errors?.required">Mobile number is required</div>
                        <div *ngIf="getform.txtMobile.errors?.minlength">please enter 10 digit</div>
                    </div>
                </div>
                <div class="form-group">

                    <input type="text" formControlName="txtEmail" placeholder="Email" class="form-control" [ngClass]="{ 'is-invalid': submitted && getform.txtEmail.errors }" />
                    <div *ngIf="submitted && (getform.txtEmail.errors || getform.txtEmail.touched)" class="text-danger">
                        <div *ngIf="getform.txtEmail.errors?.required">Email is required</div>
                        <div *ngIf="getform.txtEmail.errors?.email">Email must be a valid email address</div>
                    </div>
                </div>
                <div class="form-group">

                    <input type="password" formControlName="txtPassword" placeholder="Password" class="form-control" [ngClass]="{ 'is-invalid': submitted && getform.txtPassword.errors }" />
                    <div *ngIf="submitted && (getform.txtPassword.errors || getform.txtPassword.touched)" class="text-danger">
                        <div *ngIf="getform.txtPassword.errors?.required">Password is required</div>
                        <div *ngIf="getform.txtPassword.errors?.minlength">Password must be at least 6 characters</div>
                    </div>
                </div>
                <div class="form-group">
                    <button class="btn btn-primary" type="submit">Register</button>&nbsp;
                    <button class="btn btn-primary" type="reset" (click)="onReset()">Cancel</button>
                </div>

            </form>
        </div>
    </div>
</div>

That’s it.

Output

Also check, Template Driven Form With Validation In Angular 12

Shaikh Hafeezjaha

I am Shaikh Hafeezjaha. I started my journey as a .Net Developer and Learning and developing new things in IT Industries. I completed MSC(ICT) from Veer Narmad South Gujarat University.

Recent Posts

Testing hk

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Operation

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

TETS NEW

test

3 years ago