**Angular Reactive Form Validator**
npm install ng-reactive-form-validatorAngular Reactive Form Validator
To install this component to an external project, follow the procedure:
1. __npm install ng-reactive-form-validator --save__
2. Add __NgReactiveFormValidatorModule__ import to your __@NgModule__ like example below
``ts
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { NgReactiveFormValidatorModule } from 'ng-reactive-form-validator';
@NgModule({
imports: [ BrowserModule, NgReactiveFormValidatorModule ],
declarations: [ AppComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule {}
`
3. If you are using __systemjs__ package loader add the following mydatepicker properties to the __System.config__:
`js
(function (global) {
System.config({
paths: {
'npm:': 'node_modules/'
},
map: {
// Other components are here...
'ng-date-format': 'npm:ng-reactive-form-validator/bundles/ng-reactive-form-validator.umd.min.js'
},
packages: {
}
});
})(this);
`
Use one of the following two options.
`ts
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators, FormControl, ValidatorFn, AbstractControl } from '@angular/forms';
import { NgReactiveFormValidatorService } from 'ng-reactive-form-validator';
@Component({
selector: 'app-profile-form',
templateUrl: './profile-form.component.html',
styleUrls: ['./profile-form.component.css']
})
export class ProfileFormComponent implements OnInit {
public formObj: FormGroup;
private _formErrorMessage = {
firstName: {
required: 'You have to mention first name'
},
lastName: {
required: 'You have to mention last name'
},
email: {
required: 'You have to mention email',
email: 'Your email id is not valid'
},
phoneNo: {
required: 'Phone no is required'
},
cardNo: {
required: 'Card no is required',
cardLength: 'Please enter 16 digits card no',
}
};
public formError: any = {};
constructor(
public formBuilder: FormBuilder,
public validatorService: NgReactiveFormValidatorService
) { }
ngOnInit() {
this.formObj = this.formBuilder.group({
firstName: [null, Validators.required],
middleName: [null, Validators.required],
lastName: [null, Validators.required],
email: [null, [Validators.required, Validators.email]],
phoneNo: [null, Validators.required],
cardNo: [null, [Validators.required, this.cardLength(16, 16)]]
});
}
cardLength(min: number, max: number): ValidatorFn {
return (control: AbstractControl): { [key: string]: boolean } | null => {
if (control.value !== undefined) {
if (control.value !== null) {
if ( (control.value.toString().length < min) ||
(control.value.toString().length > max) ) {
return { 'cardLength': true };
} else {
return null;
}
} else {
return null;
}
}
return null;
};
}
saveForm() {
if (this.formObj.valid) {
console.log(this.formObj.value);
} else {
this.formError = this.validatorService.validationError(this.formObj, this._formErrorMessage);
}
}
}
`
`html``