I have a form group in my Angular form. I would like to apply a custom "blacklist" validator to the entire group, not on each field.
Is there a proper way to check that each and every field passes a validator without applying it to each controller? I guess it would be validating the group instead of every field separately. Is that possible?
Right now I am doing:
this.form = this.fb.group({
firstName: ['Ben', [Validators.required, AlphaValidator]],
lastName: this.fb.control('Racicot', [Validators.required, Validators.maxLength(30), AlphaValidator.invalidAlpha ]),
}, { validator: Blacklist });
But am getting errors. Assumably because the blacklist validator I have is not for a group but a control. Should I be focusing on changing the Validator to check every control in the form or doing the group validation different?
Here's the validator I built:
import { AbstractControl } from '@angular/forms';
const blacklist = [ // bunch of bad words ];
export function Blacklist(control: AbstractControl) {
let comment = control.value.split(' ');
// blacklist.includes(comment[i]); // es6
for (let i = 0, j = comment.length; i < j; i++ ) {
if (blacklist.indexOf(comment[i]) > -1) {
console.log(comment[i]);
return true;
} else {
return false;
}
}
}
You should return an error object like this: return { valid: false }; if validation fails. Or null if it succeeds.