Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 7 custom validation with dynamic/updated param

I am using angular 7 with material design components

I have requirement to add requireMatch validation to mat-autocomplete.

I have created custom validation with param but param value does change dynamically.

Below is my component code.

this.stepFormGroup = this.formBuilder.group({
    AccessCode: ["", [Validators.required, this.requireMatch(this.accessCodeList)]]
});

////require-match validation for access-code
requireMatch = (accessCodes: string[]) => {
    return (control: FormControl) => {
        const selection: any = control.value;
        console.log("accessCodes", accessCodes, "selection", selection);
        if (accessCodes.indexOf(selection)===-1) {
            return { requireMatch: true };
        }
        return null;
    }
}

Issue i am facing that i am always getting empty(init) in accessCodes inside requireMatch.

Changes of this.accessCodeList does not reflect to validator.

Meaning after changing this.accessCodeList it doesn't get updated array in requireMatch validator.

So anyone have any idea about how to pass dynamic param in custom-validator?

like image 666
Ankur Akvaliya Avatar asked Jan 26 '23 13:01

Ankur Akvaliya


1 Answers

You need to bind the validation function when you call it like this otherwise validator function will not bind the input accessList

[Validators.required, this.requireMatch(this.accessCodeList).bind(this)]

Also if you want to restrict some word in the field you can have a look one of my npm package here https://www.npmjs.com/package/ng4-validation

like image 188
Manzurul Avatar answered Feb 05 '23 18:02

Manzurul