I am trying implement custom validator into generic validator class, Basically I am aware of that to write normal custom validator in suppurate class but here facing a bit confusion to write in generic validator class. If any one knows please help me out.
Here is my generic-validator.ts file
import { FormGroup } from '@angular/forms';
// Generic validator for Reactive forms
// Implemented as a class, not a service, so it can retain state for multiple forms.
export class GenericValidator {
// Provide the set of valid validation messages
// Stucture:
// controlName1: {
// validationRuleName1: 'Validation Message.',
// validationRuleName2: 'Validation Message.'
// },
// controlName2: {
// validationRuleName1: 'Validation Message.',
// validationRuleName2: 'Validation Message.'
// }
constructor(private validationMessages: { [key: string]: { [key: string]: string } }) {
}
// Processes each control within a FormGroup
// And returns a set of validation messages to display
// Structure
// controlName1: 'Validation Message.',
// controlName2: 'Validation Message.'
processMessages(container: FormGroup): { [key: string]: string } {
let messages = {};
for (let controlKey in container.controls) {
if (container.controls.hasOwnProperty(controlKey)) {
let c = container.controls[controlKey];
// If it is a FormGroup, process its child controls.
if (c instanceof FormGroup) {
let childMessages = this.processMessages(c);
Object.assign(messages, childMessages);
} else {
// Only validate if there are validation messages for the control
if (this.validationMessages[controlKey]) {
messages[controlKey] = '';
if ((c.dirty || c.touched) &&
c.errors) {
for (let messageKey in c.errors) {
if (c.errors.hasOwnProperty(messageKey) &&
this.validationMessages[controlKey][messageKey]) {
messages[controlKey] += this.validationMessages[controlKey][messageKey];
}
}
}
}
}
}
}
return messages;
}
}
Here these are my parameters for custom validator i.e say : '22,3333,4,555,66' , [2,5] first one is comma separated string ... which might have entries of 2 or 5 long Here the condition is each comma suppurated string must be >2.
When I write custom validators it is typically to use with reactive forms. My custom validators are in a class that extends Validators from @angular/forms module. With this, you return null if the validation is good, and an object if it's bad.The following checks for invalid characters.
Make a FormErrorService that builds up your error message:
Where you're building the form in your comopnent:
Now in your HTML: