Robin Dijkhof
Robin Dijkhof

Reputation: 19288

Angular2 how to pass a parameter into a custom form control validator?

I wrote a very simple form control validator:

import { Directive } from '@angular/core';
import { AbstractControl, NG_VALIDATORS } from '@angular/forms';

function checkboxRequiredValidator(c: AbstractControl) {
    return c.value ? null : {
        required: true
    };
}



@Directive({
    selector: '[checkbox-required-validator]',
    providers: [
        { provide: NG_VALIDATORS, multi: true, useValue: checkboxRequiredValidator }
    ]
})
export class CheckboxRequiredValidator {

}

I would like to pass a message parameter to it which I can return. I tried this, but it won't work:

function checkboxRequiredValidator(c: AbstractControl, msg) {
    return c.value ? null : {
        message: msg
    };
}


@Directive({
    selector: '[checkbox-required-validator]',
    providers: [
        { provide: NG_VALIDATORS, multi: true, useValue: checkboxRequiredValidator }
    ]
})
export class CheckboxRequiredValidator {
    @Input('checkbox-required-validator') msg:  = 'default message';

}

Any help would be appreciated

Upvotes: 6

Views: 9594

Answers (2)

rotemx
rotemx

Reputation: 954

you can change your existing function and add an agrument to the closure, you can also add it to your own custom validators class like so (and for example write a maxVal function) :

export class MyValidators
{
        public static maxVal(maxVal: number) {
        return (c: FormControl) => {
            return c.value > maxVal ?
                { 'maxVal': { 'MaxValue': maxVal, 'actualValue': c.value } } :
                null;           
        }
    }

and then use it in your FormControl, and send the argument(for example, 100) to the validator function:

let fc:FormControl = new FormControl('name', MyValidators.maxVal(100));

Upvotes: 8

Paul Samsotha
Paul Samsotha

Reputation: 209012

You can make the directive itself the validator. That way you can use the message input.

import { forwardRef } from '@angular/core';
import { Validator } from '@angular/forms';

@Directive({
  selector: '[checkbox-required-validator]',
  providers: [
    { 
      provide: NG_VALIDATORS,
      multi: true,
      useExisting: forwardRef(() => CheckboxRequiredValidator )
    }
  ]
})
export class CheckboxRequiredValidator implements Validator {
  @Input('checkbox-required-validator') msg  = 'default message';

  validate(c: AbstractControl) {
    return c.value ? null : {
      required: this.msg
    };
  }
}

Upvotes: 5

Related Questions