<!-- main app container -->
<div class="jumbotron">
<div class="container">
<div class="row">
<div class="col-md-6 offset-md-3">
<h3>Angular 6 Custom Form Validation</h3>
<form [formGroup]="registerForm" (ngSubmit)="onSubmit()">
<div class="form-group">
<label>Password</label>
<input type="text" formControlName="password" class="form-control" [ngClass]="{ 'is-invalid': submitted && f.password.errors }" />
<div *ngIf="submitted && f.password.errors" class="invalid-feedback">
<div *ngIf="f.password.errors.required">Password is required</div>
</div>
</div>
<div class="form-group">
<label>Compare Password</label>
<input type="text" formControlName="comparepassword" class="form-control" [ngClass]="{ 'is-invalid': f.comparepassword.errors }" />
<div *ngIf="f.comparepassword.errors" class="invalid-feedback">
<div *ngIf="f.comparepassword.errors.matchPassword">Password not match</div>
</div>
</div>
<div class="form-group">
<button class="btn btn-primary">Register</button>
</div>
</form>
</div>
</div>
</div>
</div>
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators, AbstractControl, ValidationErrors } from '@angular/forms';
@Component({
selector: 'app',
templateUrl: 'app.component.html'
})
export class AppComponent implements OnInit {
registerForm: FormGroup;
submitted = false;
constructor(private formBuilder: FormBuilder) { }
ngOnInit() {
this.registerForm = this.formBuilder.group({
password: ['', Validators.required],
comparepassword: ['', comparepassword]
});
}
// convenience getter for easy access to form fields
get f() { return this.registerForm.controls; }
onSubmit() {
this.submitted = true;
// stop here if form is invalid
if (this.registerForm.invalid) {
return;
}
alert('SUCCESS!! :-)
' + JSON.stringify(this.registerForm.value))
}
}
function comparepassword(control: AbstractControl): ValidationErrors {
if (control.parent != undefined) {
var password: string = control.parent.get("password").value;
var cpassword: string = control.parent.get("comparepassword").value;
if (password !== cpassword) {
return { matchPassword: true };
}
}
return null;
}