MartaGalve
MartaGalve

Reputation: 1226

Pass parameters to a custom validator added to FormGroup

I am trying to add a custom validator to a FormGroup, so I can compare multiple input fields inside the form. It works if I hardcode the names of the input fields inside the validator, but I haven't found a way of passing these names as parameters.

Is this possible?

// validator

export function TestValidator (controlName: string, secondControlName: string, thirdControlName: string) {

    return (form: FormGroup) => {
        // OK
        console.log(form);

        // OK
        console.log(controlName);

        // undefined
        console.log(secondControlName);
        console.log(thirdControlName);
        ...
    }
}

// form service

...
this.form = this.formBuilderService.group({...}, {validator: testValidator('name1', 'name2', 'name3')});

All the examples I've seen that add validators to the fromGroup use no parameters.

Upvotes: 0

Views: 2863

Answers (1)

Basim E-Darussalam
Basim E-Darussalam

Reputation: 71

My custom validator code may help to solve your issue

export function matchOtherValidator(otherControlName: string) {

let thisControl: FormControl;
let otherControl: FormControl;

return function matchOtherValidate(control: FormControl) {

    if (!control.parent) {
        return null;
    }

    // Initializing the validator.
    if (!thisControl) {
        thisControl = control;


   otherControl = control.parent.get(otherControlName) as FormControl;
        if (!otherControl) {
            throw new Error('matchOtherValidator(): other control is not 
   found in parent group');
        }
        otherControl.valueChanges.subscribe(() => {
            thisControl.updateValueAndValidity();
        });
    }

    if (!otherControl) {
        return null;
    }

    if (otherControl.value > thisControl.value) {
        return {
            dateError: true
        };
    }

    return null;

}

here you can see how I got other control by passing another control name to check which one is bigger you can use this same technique in your validation function.

Upvotes: 1

Related Questions