Learn how to create forms with validations in angular 2

Angular has provided us with modules with which we can not only write forms but also make them reactive.

Let see how Angular 2/ Angular 4 helps us create forms.

Modules to be imported

Firstly we need two modules

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

and add them to the @NgModule’s import section.

Adding FormBuilder and FormGroup

The component where you need to include you from should import “FormBuilder and FormGroup” from @angular/forms;

FormBuilder helps define us the controls to be used in our form. With FormBuilder we can not only create our form controls but also apply validations in our forms.

let us create a component named forms and integrate angular 2 form into it.

forms.component.ts

import {Component, ElementRef, OnInit, HostListener, AfterViewInit, Inject} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from "@angular/forms";

@Component({
  selector: 'form-component'
})

export class FormComponent {

  loginForm: FormGroup;

  constructor(@Inject(FormBuilder) fb: FormBuilder) {
   
    this.loginForm = fb.group({
      email: [null, [Validators.required, Validators.pattern(/^(.*)@(\w*)\.(\w*)$/)]],   //With validators applied email patterns
      mobile: [null, [Validators.required, Validators.pattern(/^\d{10}$/)]],             
      password: [null, Validators.required]
    });
  }

  loginUser() {
   //Do things after login
  }
}

 

In above section of code we have create a form group named “loginFrom” using FormBuilder class group method.

Just pass an object with all the controls you wanted your forms to have. With these form controls you can pass the initial values to these controls or you can make them empty by passing “null” values.

For these controls follow some validations, you can make use of html attributes in our html file like required, pattern etc. or we can use  Validators class provided by angular forms. This class contains several methods for validations and they are directly applied to the controls of the form group.

We have used Validators.required for making email field required and also we want out email to follow a particular pattern so we have used Validators.pattern method and provide it a regex pattern for email.

 

Designing our forms in html

Let us create out html file for our form component:

forms.component.html :

<form [formGroup]="loginForm" (submit)="loginUser()">
  <div class="form-group">
    <input type="email" class="form-control" placeholder="Email" name="email"
           [formControl]="loginForm.controls['email']">
    <div class="ui-message ui-messages-error ui-corner-all"
         [hidden]="!(loginForm.controls['email'].invalid && loginForm.controls['email'].dirty)">
      <i class="fa fa-close"></i> Please enter your email
    </div>
  </div>
  <div class="form-group">
    <input type="password" class="form-control" placeholder="Mobile" name="mobile"
           [formControl]="loginForm.controls['mobile']">
    <div class="ui-message ui-messages-error ui-corner-all"
         [hidden]="!(loginForm.controls['mobile'].invalid && loginForm.controls['mobile'].dirty)">
      <i class="fa fa-close"></i> Please enter your mobile number
    </div>
  </div>
  <div class="form-group">
    <input type="password" class="form-control" placeholder="Password" name="password"
           [formControl]="loginForm.controls['password']">
    <div class="ui-message ui-messages-error ui-corner-all"
         [hidden]="!(loginForm.controls['password'].invalid && loginForm.controls['password'].dirty)">
      <i class="fa fa-close"></i> Please enter your password
    </div>
  </div>
 
  <div class="form-group">
    <button type="submit" [disabled]="loginForm.invalid"
            class="btn btn-primary-alt full_width">
      Login
    </button>
  </div>
  </div>
</form>

 

In above html file we have create a form and passed into it formGroup directive of the ReactiveForms  module and pass into it the form group create in the .ts file which is “loginForm“.

Now create form elements using the form controls of the loginForm. For binding the formgroup controls to the html input or select elements we make use of the formControl directive. This bind the value to the form group controls.

Example:

 <input type="email" class="form-control" placeholder="Email" name="email"
           [formControl]="loginForm.controls['email']">

loginForm group provides all the controls using  its “controls” property. Also do not forget to provide a name attribute to each of the form control used in your form otherwise directive “formControl” will throw errors.

Now that we have created a from with all the bindings, let us now apply some validations to the form.

Validations on form

FormGroup apply a lot of validation methods in its controls which help apply validations on these controls.

Some of these are:

  1. valid
  2. invalid
  3. dirty
  4. pristine
  5. touched
  6. untouched

we can use these validation methods on either of the form controls or form group.

Example:  using validator methods on form controls –

loginForm.controls['email'].invalid

This will return a boolean value telling us weather the email control is invalid or not.

To use it on the form group or complete form:

loginForm.invalid

This also returns a boolean value specifying weather all the form controls are valid or not. This is the forms complete validator.

By using these validation methods we can show our validation messages .

Enjoy writing form in angular !!

 


Posted

in

by

Recent Post

  • Future Trends in AI Chatbots: What to Expect in the Next Decade

    Artificial Intelligence (AI) chatbots have become indispensable across industries. The absolute conversational capabilities of AI chatbots are enhancing customer engagement, streamlining operations, and transforming how businesses interact with users. As technology evolves, the future of AI chatbots holds revolutionary advancements that will redefine their capabilities. So, let’s start with exploring the AI chatbot trends: Future […]

  • Linguistics and NLP: Enhancing AI Chatbots for Multilingual Support

    In today’s interconnected world, businesses and individuals often communicate across linguistic boundaries. The growing need for seamless communication has driven significant advancements in artificial intelligence (AI), particularly in natural language processing (NLP) and linguistics. AI chatbots with multilingual support, are revolutionizing global customer engagement and service delivery. This blog explores how linguistics and NLP are […]

  • How Reinforcement Learning is Shaping the Next Generation of AI Chatbots?

    AI chatbots are no longer just about answering “What are your working hours?” or guiding users through FAQs. They’re becoming conversation partners, problem solvers and even reporting managers and sales agents. What’s driving this transformation? Enter Reinforcement Learning (RL)—a type of machine learning that’s changing the way chatbots think, learn, and respond. At Codalien Technologies, […]

  • AI Chatbots for Sales Team Automation: The Critical Role of AI Sales Assistants in Automating Your Sales Team

    Sales teams are the heart of any successful business, but managing them effectively can often feel like trying to juggle flaming swords. The constant pressure to generate leads, maintain relationships, and close deals leaves your team overwhelmed, spending more time on administrative tasks than actual selling. Here’s where AI-powered sales assistants step in to completely […]

  • Transforming HR with AI Assistants: The Comprehensive Guide

    The role of Human Resources (HR) is critical for the smooth functioning of any organization, from handling administrative tasks to shaping workplace culture and driving strategic decisions. However, traditional methods often fall short of meeting the demands of a modern, dynamic workforce. This is where our Human Resource AI assistants enter —a game-changing tool that […]

  • How Conversational AI Chatbots Improve Conversion Rates in E-Commerce?

    The digital shopping experience has evolved, with Conversational AI Chatbots revolutionizing customer interactions in e-commerce. These AI-powered systems offer personalized, real-time communication with customers, streamlining the buying process and increasing conversion rates. But how do Conversational AI Chatbots improve e-commerce conversion rates, and what are the real benefits for customers? In this blog, we’ll break […]

Click to Copy