Types of form validation in angular with example

Form validation in angular with example


Hello, dear visitor or reader nice to see you here our team always trying to give you valuable contents everytime so that you learn more in easy way .i am senior software engineer and i have enough experience on angular and i am sharing my experience in Web platform and many more here.

Introduction to angular:


     hello dear learner and visitor thanks for choosing us .Angular is the JavaScript open source SPA(Single Page Application) framework .we can create our application using its MVVC architecture with advanced feature ,easy way of implementation and configuration. In angular to make any web application oor hybrid is very easy because the structure of of project is so easy to understand for any web developer.we can also make hybrid and native application with the help of other framework with angular.We have started a series of Angular you can search you requires topic of angular or you can go through all the course free of cost.Our goal is to help you and give best content that can be understandable by beginners and others.

So let's start the topic about for validation.

Requirements:

1.Basic understanding of typescript
2.basics of HTML

What is form validation ?


So form validation is nothing but verifying the user inputs whether the inputs are acceptable or in appropriate format .So fom validation is very good topic and most important tpic in any framework basically in any web application frameworks because in every web application there should a form. user inputs are valuable informations that can be used in future so every input should be validated .

  In javascript it is very easy to achieve form validation by getting value from input fields and applying logics to validate them.But in angular we can achieve them in more easy way .

Form validation in angular 11,12,13 with example


Types of Validation in angular 

there are two types of form validations in angular 

1.template driven form validation
2.Reactive form validation

Both works in same way but the configuration of both the validation technique are different .So let's understand one by one with one sample example .

Template driven validation

Template driven form validation can be achieved by ngModel directives which we have discussed on our previous article.ngModel basically make a communication between HTML form and model view means simply we can say this helps in two way data binding .And with help of some other directives we can achieve template driven form validations .

Example form for template driven form vaidation.

if we want to add any form validation in angular application we have to import the FormsModule to the import section of our app module this will make available all required configuration and implementation to the components.

 <form #myForm="ngForm" (ngSubmit)="onSubmit(myForm.value)">
        <p>
            <label>First Name:</label>
            <input type="text" [(ngModel)]="firstname" required>
        </p>
        <p>
            <label>Password:</label>
            <input type="password" [(ngModel)]="password" required>
        </p>
        <p>
            <button type="submit" [disabled]="!myForm.valid">Submit Form</button>
        </p>
    </form>

Here in this example we have created a sample form with a component reference variable and with some form fields .

ngForm- this directives will create a component reference variable with the help this variable we can track whole form fields values.

ngModel- As we hve discussed this will help us to make a connection between form and model view and whatever value we will insert here that can be tracked by component.

ngSubmit - this will help to submit the whole forms fields data with a method of our component class.

required - required is a attribute which will indicate a input field that this field is mandatory and can't be null.

Let's see how we are handling these values inside component.

@Component({
    selector: "app-root",
    templateUrl: 'template-driven-form.html'
})
export class AppComponent{

firstname:any;
password:any;


    userInputs = {
        firstName: this.firstNamem
        password:  this.password
    };
    
    onSubmit(userInputs) {
     //   User logic here with form data like api call ............
    }

}


Here inside the appcomponent ts file we have added two variable with same name as we have added inside form fields with ngModel .And with the user input we have prepared a JSON that can be used anywere as form data.

Advantages and disadvantages of template driven forms

1.Template driven validation are easy to implement .
2.With help of only some directives we can achieve this validation.
3.But using this form validation we can't add custom validations only some static validation are there to add custom validation we have write more complex code .
3.We can't show custom errors or fields friendly errors to users.

Reactive Form Validation

if we want to add any form validation in angular application we have to import the ReactiveFormsModule to the import section of our app module this will make available all required configuration and implementation to the components.

Example of Reactive form validation

 <form [formGroup]="form" (ngSubmit)="onSubmit()">
        <p>
            <label>First Name:</label>
            <input type="text" formControlName="firstName">
        </p>
        <p>
            <label>Password:</label>
            <input type="password" formControlName="password">
        </p>
        <p>
            <button type="submit" [disabled]="!form.valid">Submit</button>
        </p>
    </form>

Like template driven form validation we can use some directives here to achieve the validation or to get the user inputs .

FormGroup - this will refere to the component variable .

ngSubmit - This will help to submit the form data .

formControlname - This is the directive which will point to a component variable .

Let's see what changes we need to o do inside component to handle the validation .


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

@Component({
    selector: "app-root",
    templateUrl: 'app.componen.html'
})
export class appComponent{
    
    form = new FormGroup({
            "firstName": new FormControl("", Validators.required),
            "password": new FormControl("", Validators.required),
    });
    
    onSubmit() {
        console.log(this.form);
    }
}


here are creating one form by instantiating FormGroup and now as we have control over the form now we can validate the it's controls or fields .Here we have just added validation for required validation we can also add custom validation for mobiles number or for emails or many more .


Advantages and disadvantages of Reactive Form validation

1.We can add custom validations.
2.we can show custom validation errors so that user can understand what type of value need to be insert.
3.lengthy to implement but faster .

thanks you so much for visiting our site comment us your experience and if you have nay query contact us .


Post a Comment

Previous Post Next Post