In this article, we going to learn about how to create a signup form with validating client-side errors.
Overview:
- Add ReactiveFormModule in module.ts
- Create and Design component
- Import FormBuilder in component.ts file
- Add password validator
Add ReactiveFormModule in module.ts
Code: app.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { BrowserModule } from '@angular/platform-browser';
import { EcommerceRoutingModule } from './ecommerce-routing.module';
import { MainComponent } from './main/main.component';
import { ReactiveFormsModule } from '@angular/forms';
@NgModule({
declarations: [MainComponent],
imports: [
CommonModule,
BrowserModule,
EcommerceRoutingModule,
ReactiveFormsModule
],
bootstrap: [MainComponent],
})
export class EcommerceModule { }
Create and Design component
In terminal type: ng g c signup to create a new component for sign up. After created the component. you must add bootstrap for styling. If you don’t know how to add bootstrap in angular, then go to this article and check that once and come back.
Code: signup.component.html
<section>
<div class="container-fluid">
<div class="row">
<div class="col-12 col-sm-6 " style="height:100vh;">
<div class="d-flex align-items-center" style="height:100%">
<img src="assets/image/signupCat.svg" class="img-fluid" style="vertical-align:middle" />
</div>
</div>
<div class="col-12 col-sm-6">
<div class="d-flex align-items-center justify-content-center" style="height:100%">
<div style="width:70%">
<form class="form-horizontal" [formGroup]='signUpForm' (submit)='onSubmit()'>
<div class="d-flex col-sm-8 justify-content-center">
<div class="text-dark pl-5" style="font-weight:bold;font-size:20px;">Sign Up!</div>
</div>
<div class="form-group mb-4 position-relative">
<label for="name" class="col-sm-2 control-label">Name</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="name" placeholder="Name" formControlName="name" [ngClass]="{'border-danger': (!(signUpForm.controls['name'].valid) && isSubmitted)?true :false}"/>
</div>
<div class="text-danger error" *ngIf="!signUpForm.controls['name'].valid && isSubmitted">Name is required</div>
</div>
<div class="form-group mb-4 position-relative">
<label for="inputEmail3" class="col-sm-2 control-label">Email</label>
<div class="col-sm-10">
<input type="email" class="form-control" id="inputEmail3" placeholder="Email" [pattern]="emailPattern" formControlName="email" [ngClass]="{'border-danger': (!(signUpForm.controls['email'].valid) && isSubmitted)?true :false}" />
</div>
<div class="text-danger error" *ngIf="signUpForm.controls['email'].invalid && isSubmitted">
<div *ngIf="signUpForm.controls['email'].errors.required">
Email is required
</div>
<div *ngIf="signUpForm.controls['email'].errors.pattern">
Invalid email
</div>
</div>
</div>
<div class="form-group mb-4 position-relative">
<label for="inputPassword3" class="col-sm-2 control-label">Password</label>
<div class="col-sm-10">
<input type="password" class="form-control" id="inputPassword3" placeholder="Password" formControlName="password" [ngClass]="{'border-danger': (!(signUpForm.controls['password'].valid) && isSubmitted)?true :false}" />
</div>
<div class="text-danger error" *ngIf="signUpForm.controls['password'].invalid && isSubmitted">
<div *ngIf="signUpForm.controls['password'].errors.required">
Password is required
</div>
<div *ngIf="signUpForm.controls['password'].errors.minlength">
Password must be minimum 8 character
</div>
</div>
</div>
<div class="form-group mb-4 position-relative">
<label for="inputPassword4" class="col-sm-2 control-label">Confirm Password</label>
<div class="col-sm-10">
<input type="password" class="form-control" id="inputPassword4" placeholder="Confirm Password" formControlName="confirmpassword" [ngClass]="{'border-danger': (!(signUpForm.controls['confirmpassword'].valid) && isSubmitted)?true :false}"/>
</div>
<div class="text-danger error" *ngIf="!(signUpForm.controls['confirmpassword'].valid) && isSubmitted">
<div class="text-danger" *ngIf="!(signUpForm.controls['confirmpassword'].valid) || signUpForm.get('confirmpassword').errors &&
signUpForm.get('confirmpassword').errors.confirmpassword && isSubmitted || signUpForm.get('confirmpassword').errors &&
signUpForm.get('confirmpassword').errors.confirmpassword && (signUpForm.controls['confirmpassword'].dirty && isSubmitted || signUpForm.controls['confirmpassword'].touched)">
Password does not match
</div>
</div>
</div>
<div class="form-group mb-4 position-relative">
<div class="col-sm-offset-2 col-sm-10 text-center">
<button type="submit" class="btn btn-dark" >Sign Up</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</section>
If you need image which I used is fully free. Go to undraw.co , then click on illustration and search welcome cats. You can use anywhere its fully free vector image. you can have the option of download to both SVG and png. We can also change the color of the illustration as a need.
Code:signup.component.css
/* Change the white to any color ;) */
input:-webkit-autofill,
input:-webkit-autofill:hover,
input:-webkit-autofill:focus,
input:-webkit-autofill:active {
-webkit-box-shadow: 0 0 0 30px white inset !important;
}
.error{
position:absolute;
left:15px;
}
Then go to the important todo. Import form builder and validators to our sign up module.
Code: singup.component.ts
import { Component, OnInit } from '@angular/core';
import { FormBuilder, Validators } from '@angular/forms';
import { ConfirmPasswordValidator } from './passwordValidator';
@Component({
selector: 'app-main',
templateUrl: './main.component.html',
styleUrls: ['./main.component.css']
})
export class MainComponent implements OnInit {
public signUpForm;
public isSubmitted = false;
emailPattern = '^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$';
constructor(
private formBuilder: FormBuilder) { }
ngOnInit(): void {
this.signUpForm = this.formBuilder.group({
name: ['', Validators.required],
email: ['', [Validators.required, Validators.email]],
password: ['', [Validators.required, Validators.minLength(8)]],
confirmpassword: ['', Validators.required],
},{ validator: ConfirmPasswordValidator.MatchPassword });
}
onSubmit(){
this.isSubmitted = true;
if(this.signUpForm.invalid){
return;
}
alert(JSON.stringify(this.signUpForm.value));
}
}
For password validation, we create another file and imported to this component.ts file
Example: create a file called passwordValidator.ts and add the code below
Code: passwordValidator.ts
import { AbstractControl } from '@angular/forms';
export class ConfirmPasswordValidator {
static MatchPassword(control: AbstractControl) {
const password = control.get('password').value;
const confirmpassword = control.get('confirmpassword').value;
if (password !== confirmpassword) {
control.get('confirmpassword').setErrors({ Confirmpassword: true });
} else {
return null;
}
}
}
The above file is important to the password validators to check password matches or not. Then run the code. I hope this will help. You can easily use this code for any project you want.
If any queries about this signup form. Please ping in the comment and I will help you to solve the error. Have a good day!