Angular form custom validator messages causing error

208 views Asked by At

I have a custom validator for blacklisting words from form controllers:

import { AbstractControl } from '@angular/forms';

const blacklist = ['poop']; 
export function Blacklist(control: AbstractControl) {

    let comment = control.value.split(' ');
    for (let i = 0, j = comment.length; i < j; i++ ) {
        if (blacklist.indexOf(comment[i]) !== -1) { // -1 = is no match in array
            return {
                validateBlacklist: {
                    blacklist: false
                }
            }
        } else {

        }
    }
    return null;
}

Everything works great! But when I try to do a validation message I get: ERROR TypeError: Cannot read property 'validateBlacklist' of null on every key up unless it's a word in my blacklist array...

From this:

<div *ngIf="commentForm.controls['newComment'].errors.validateBlacklist && commentForm.controls['newComment'].touched">Error</div>

What am I doing wrong?!

1

There are 1 answers

3
pa7ryk On

Error occurred due to ngIf condition.

Object errors doesn't have validateBlacklist object at the time of check and it's current value is null. Try console.log(this.commentForm.controls['newComment'].errors) first.

So it should look like this:

public isErrorOccurred(): boolean {
    if(
        'validateBlacklist' in this.commentForm.controls['newComment'].errors &&
        this.commentForm.controls['newComment'].touched
    ) {
        return 'blackList' in this.commentForm.controls['newComment'].errors.validateBlacklist;
    }
}

ngIf:

*ngIf="isErrorOccurred()"