Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 384
Robin Dijkhof Avatar asked Oct 14 '16 07:10

Robin Dijkhof


2 Answers

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));
like image 71
rotemx Avatar answered Oct 21 '22 22:10

rotemx


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
    };
  }
}
like image 5
Paul Samsotha Avatar answered Oct 21 '22 20:10

Paul Samsotha