Angular13 Reactive Form Validation

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

1) Create Steps for app.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 into the AppComponent class.


  userForm!: FormGroup;
  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 data.


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

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


import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {

  userForm!: FormGroup;
  submitted = false;
  constructor( protected readonly fb:FormBuilder) {
  }

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

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

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

  submitUserform(){
  this.submitted = true;
  if(this.userForm.invalid){
    return;
  }
  let user_name=  this.userForm.controls['userName'].value;
  let user_age=  this.userForm.controls['userAge'].value;
  console.log("username: "+user_name);
  console.log("userage: "+user_age);  
}

}

2) Create Steps for app.component.html file

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


<input type="text" formControlName="userAge"  [ngClass]= "{ 'is-invalid': submitted && formData['userAge'].errors}"/>             
<div *ngIf="submitted && formData['userAge'].errors" class="invalid-feedback">
    <div *ngIf="formData['userAge'].errors['required']">User Age is required</div>
    <div *ngIf="formData['userAge'].errors['pattern']">User Age must be  numeric</div>
</div>  

Now, complete the app.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="user" [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" [ngClass]= "{ 'is-invalid': submitted && formData['userName'].errors}" /> 
                <div *ngIf="submitted && formData['userName'].errors" class="invalid-feedback">
                  <div *ngIf="formData['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"  [ngClass]= "{ 'is-invalid': submitted && formData['userAge'].errors}"/>             
                <div *ngIf="submitted && formData['userAge'].errors" class="invalid-feedback">
                  <div *ngIf="formData['userAge'].errors['required']">User Age is required</div>
                  <div *ngIf="formData['userAge'].errors['pattern']">User Age must be  numeric</div>
                </div>   
              </div>
            </div>
            <div class="col-md-12 row" style="height: 15px"></div>
            <div  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.