Angular Reactive Form Validation

Angular Reactive Form Validation is implemented into the Angular Component typescript file like componentName.component.ts file.
I have already created users component, so now I am creating validation for Reactive form. There are some steps to create the Validations.

1) Create Steps for users.component.ts file

Step1) Firstly import Validators from @angular/forms


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

Step2) define the validation on the field name in the class.


  this.userForm = this.fb.group({
      userName: ['', [Validators.required]],
      userAge: ['', [Validators.required, Validators.pattern(/^-?(0|[1-9]\d*)?$/)]]
    });

Note:- You can create multiple validation on the field, we created two validation on userAge, First Validation is used to userAge must be validate and second Validation is used to define the userAge must be numeric only.

Step3) get the form fields value.


get formFieldValues() { return this.userForm.controls; }

After, create the validation then complete users.component.ts file


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


@Component({
  selector: 'app-users',
  templateUrl: './users.component.html',
  styleUrls: ['./users.component.scss']
})

export class UsersComponent implements OnInit {
  public userForm!: FormGroup;
  submitted = false;
  constructor(protected readonly fb: FormBuilder) {

  }

  ngOnInit(): void {
    this.setupUserForm();
  }

  setupUserForm() {
    this.userForm = this.fb.group({
      userName: ['', [Validators.required]],
      userAge: ['', [Validators.required, Validators.pattern(/^-?(0|[1-9]\d*)?$/)]]
    });
  }

  // get form fields value
  get formFieldValues() { return this.userForm.controls; }

  submitUserform() {
    this.submitted = true;
    if (this.userForm.invalid) {
      return;
    }
    console.log(this.userForm.value);

    let user_name = this.userForm.controls['userName'].value;
    let user_age = this.userForm.controls['userAge'].value;

    console.log("user_name+++", user_name);
    console.log("user_age+++", user_age);

  }

}

2) Create Steps for users.component.html file

Step1) implement the validation under the validate fields through *ngIf condition.


<div *ngIf="submitted && formFieldValues.userAge.errors" class="invalid-feedback">
    <div *ngIf="formFieldValues.userAge.errors.required">User Age is required</div>
    <div *ngIf="formFieldValues.userAge.errors.pattern">User Age must be  numeric</div>
</div>

Now, complete the users.component.html file


<div class="container">
    <div class="col-md-3"></div>
    <div class="col-md-6 text-center">
      <h1>Add User</h1>
      <form id="" [formGroup]="userForm" class="form">
        <div class="col-md-12 row">
          <div class="col-md-4">
            <label>User Name</label>
          </div>
          <div class="col-md-8">
            <input type="text" formControlName="userName"  class="input-bordered form-control" />
            <div *ngIf="submitted && formFieldValues.userName.errors" class="invalid-feedback">
              <div *ngIf="formFieldValues.userName.errors.required">User Name is required</div>
  
          </div>
          </div>
        </div>
        <div class="col-md-12 row" style="height: 15px"></div>
        <div class="col-md-12 row">
          <div class="col-md-4">
            <label>User Age</label>
          </div>
          <div class="col-md-8">
            <input type="text" formControlName="userAge" class="input-bordered form-control" />
            <div *ngIf="submitted && formFieldValues.userAge.errors" class="invalid-feedback">
              <div *ngIf="formFieldValues.userAge.errors.required">User Age is required</div>
              <div *ngIf="formFieldValues.userAge.errors.pattern">User Age must be  numeric</div>
          </div>
          </div>
        </div>
        <div class="col-md-12 row" style="height: 15px"></div>
        <div class="col-md-12 row" align="center">
          <input type="submit" name="userSubmit" (click)="submitUserform()" value="Add User" />
        </div>
      </form>
    </div>
    <div class="col-md-3"></div>
  </div>
  

Create the css into the users.component.scss file.


.invalid-feedback{color:red;}

Now run the URL on the browser.


http://localhost:4200/users

5) When I click the submit button without fill the textbox value then show validation.

6) When I click the submit button after fill the string value into userAge textbox then show validation.