1

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 Answer 1

1

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()"
Sign up to request clarification or add additional context in comments.

3 Comments

it is {minlength: {requiredLength: 2, actualLength: 1}} for each keyup then when the word matches the validator it's {validateBlacklist: {blacklist: false}}
That's cool but I need to know how to show an error message for that specific error on that control. For this and learning purposes.
That's what this code do. It checks if exactly this type of error occurred and return boolean. If it exists it returns true and you can show your div. Just try to use it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.