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
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));
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
};
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With