Angular - assign custom validator to a FormGroup

Discussão em 'Angular' iniciado por Chris Halcrow, Setembro 11, 2024.

  1. I need to assign a custom validator to a FormGroup. I can do this at the time the FormGroup is created like this:

    let myForm : FormGroup;

    myForm = this.formBuilder.group({
    myControl1: defaultValue,
    myControl2: defaultValue
    }, { validator: this.comparisonValidator })

    comparisonValidator(g: FormGroup) {
    if (g.get('myControl1').value > g.get('myControl2'.value)) {
    g.controls['myControl1'].setErrors({ 'value2GreaterThanValue1': true });
    return;
    }
    }


    I have a situation though where I need to add the custom validator after I've instantiated the FormGroup, so I'm trying to do this after instantiating myForm, instead of adding the validator when the form is instantiated:

    let myForm : FormGroup;

    myForm = this.formBuilder.group({
    myControl1: defaultValue,
    myControl2: defaultValue
    })

    this.myForm.validator = this.comparisonValidator;


    This gives me a compiler error:

    Type '(g: FormGroup) => void' is not assignable to type 'ValidatorFn'.
    Type 'void' is not assignable to type 'ValidationErrors'.


    How do I assign a validator to my FormGroup so that the formGroup is passed as the argument to my comparisonValidator function?

    Update - I've added a line showing where I'm doing a setErrors in my comparisonValidator, to make it clearer exactly how I'm trying to set a validation error.

    Continue reading...

Compartilhe esta Página