Angular 6 Reactive form Validation

Vikas Kohli
3 min readDec 31, 2018

--

HTML File (app.component.html)

<!-- main app container -->
<div class="register-form">
<div class="container">
<div class="row">
<div class="col-md-6 offset-md-3">
<h3>Angular 6 Reactive Form Validation</h3>
<form [formGroup]="registerForm" (ngSubmit)="onSubmit()" #regForm="ngForm" >
<div class="form-group">
<label>First Name
</label>
<input type="text" formControlName="firstName" class="form-control" [ngClass]="{ 'is-invalid': (submitted || f.firstName.touched) && f.firstName.errors }" />
<div *ngIf="((submitted ||f.firstName.touched) && f.firstName.errors)" class="invalid-input">
<div *ngIf="f.firstName.errors.required">First Name is required</div>
</div>
</div>
<div class="form-group">
<label>Last Name</label>
<input type="text" formControlName="lastName" class="form-control" [ngClass]="{ 'is-invalid': (submitted || f.lastName.touched) && f.lastName.errors }" />
<div *ngIf="((submitted ||f.lastName.touched) && f.lastName.errors)" class="invalid-input">
<div *ngIf="f.lastName.errors.required">Last Name is required</div>
</div>
</div>
<div class="form-group">
<label>Select Gender</label>
<div class="gender text-capitalize" >
<label *ngFor="let gender of genders">
<input type="radio" [value]="gender"
formControlName = "gender"
[ngClass]="{'is-invalid': submitted && f.gender.errors }">{{gender}}
</label>
</div>
<div *ngIf="submitted && f.gender.errors" class="invalid-input">
<div *ngIf="f.gender.errors.required" >Gender is required</div>
</div>
</div>
<div class="form-group">
<label>Email</label>
<input type="text" formControlName="email" class="form-control" [ngClass]="{ 'is-invalid': (submitted ||f.email.touched) && f.email.errors }" />
<div *ngIf="((submitted ||f.email.touched) && f.email.errors)" class="invalid-input">
<div *ngIf="f.email.errors.required">Email is required</div>
<div *ngIf="f.email.errors.pattern">Email must be a valid email address</div>
</div>
</div>
<div class="form-group">
<label>Password</label>
<input type="password" formControlName="password" class="form-control" [ngClass]="{ 'is-invalid': (submitted || f.password.touched) && f.password.errors }" />
<div *ngIf="((submitted ||f.password.touched) && f.password.errors)" class="invalid-input">
<div *ngIf="f.password.errors.required">Password is required</div>
<div *ngIf="f.password.errors.minlength">Password must be at least 6 characters</div>
</div>
</div>
<div formArrayName="hobbies">
<h4>Hobbies</h4>
<div class="form-group"
*ngFor="let hobbyControl of f.hobbies.controls; let i=index">
<input type="text" class="form-control"
[formControlName]="i">
</div>
<button class="btn btn-default hobby"
type="button" (click)="onAddHobby()" >Add Hobby</button>
</div>
<div class="form-group">
<button class="btn btn-primary">Register</button>
</div>
</form>
</div>
</div>
</div>
</div>
<!-- credits -->
<div class="text-center">
<p>
<a href="https://github.com/imvikaskohli/Angular-6-Reactive-Validation-Form" target="_top">Angular 6 - Reactive Forms Validation Example - Github Link</a>
</p>
<p>
<a href="https://github.com/imvikaskohli/" target="_top">Vikas Kohli - Github</a>
</p>
</div>

In the HTML file, I create a form that has the following fields:-

firstName, lastName, gender, email, password, and hobbies.

TS File(app.component.ts)

import { Component, OnInit, ViewChild } from '@angular/core';import { FormBuilder, FormGroup, Validators, FormArray, FormControl } from '@angular/forms';
import { ToastrService } from 'ngx-toastr';
@Component({
selector: 'app',
templateUrl: 'app.component.html',
styleUrls: ['app.component.scss']
})
export class AppComponent implements OnInit {registerForm: FormGroup;
submitted = false;
genders=['male','female', 'other'];
@ViewChild('regForm') myRegForm;constructor(
private formBuilder: FormBuilder,
private toastr: ToastrService
) { }
ngOnInit() { this.registerForm = this.formBuilder.group({
firstName: ['', Validators.required],
lastName: ['', Validators.required],
email: ['', [Validators.required, Validators.pattern(/^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,63})$/)]],
password: ['', [Validators.required, Validators.minLength(6)]],
gender: ['', Validators.required],
hobbies':new FormArray([])
});
}// convenience getter for easy access to form fields, if not used then in html we can use like// form.get('identity').touched"get f() { return this.registerForm.controls; }onAddHobby(){
const control=new FormControl(null,Validators.required); (<FormArray>this.registerForm.get('hobbies')).push(control);
}
onSubmit() {
this.submitted = true;
// stop here if form is invalid
if (this.registerForm.invalid) {
return;
}
this.myRegForm.resetForm();
this.submitted = false;
this.toastr.success("Registration Successfull");
}
}

Firstly we import that we need to use in the form validation. Also, I import the toaster module, because, after successful registration, I want to show the successful message.

Before showing message, I reset the form and submit button to false as well because the user is registered is successful. As I am here only discussing the form validation, that’s why I don’t need to navigate. In the real world, it will redirect to login or homepage of that application or might be any other page depending upon the project requirement.

Here, I use fromArray in the form as hobbies can be multiple, so it has to be an array

Github link:- https://github.com/imvikaskohli/Angular-6-Reactive-Validation-Form

For the demo, you can visit the following link in Stackblitz

https://angular-xtzntk.stackblitz.io

--

--

Vikas Kohli
Vikas Kohli

Written by Vikas Kohli

B.E Software Developer, Enthusiastic, Ego-surfing

No responses yet