//TestAnythingsComponent.ts
import { Component, OnInit } from '@angular/core';
import { FormControl, FormBuilder, FormGroup, Validators } from '@angular/forms';
import { IdNumberDirective } from '../directives/IdNumberDirective.directive';
@Component({
selector: 'app-test-anythings',
templateUrl: './test-anythings.component.html',
styleUrls: ['./test-anythings.component.css'],
providers:[IdNumberDirective]
})
export class TestAnythingsComponent implements OnInit {
testForm: FormGroup;
constructor(fb: FormBuilder, IdNumberDirective : IdNumberDirective) {
this.testForm = fb.group({
idNumberFormControl : new FormControl(null,
Validators.compose([
Validators.required,
Validators.minLength(3),
Validators.maxLength(8),
IdNumberDirective.customValidator()
])
),
})
}
}
//IdNumberDirective.ts
import { Directive, OnInit } from '@angular/core';
import { Validators, ValidatorFn, AbstractControl, ValidationErrors } from '@angular/forms';
@Directive({
selector: '[idNumber]'
})
export class IdNumberDirective implements OnInit {
constructor() {
}
ngOnInit() {
}
customValidator(): ValidatorFn {
Validators.nullValidator
return (control: AbstractControl): ValidationErrors | null => {
//any condition to check control value
if (control.value != "Sachin") {
//return key value pair of errors
return { "customError": { inValid: true, errMsg: 'Invalid Value' } };
}
return null;
}
}
}
//test-anythings.component.html
<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code> <form [formGroup]="testForm">
<input idNumber formControlName="idNumberFormControl" />
<div *ngIf="testForm.get('idNumberFormControl').invalid && testForm.get('idNumberFormControl').errors.customError.inValid"
style="color:red">
{{testForm.get('idNumberFormControl').errors.customError.errMsg}}
</div>
<button type="submit">submit</button>
</form>