Angular2 how to pass parameter to custom form validation template?

I wrote a very simple form validation mechanism:

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 that I can return. I tried this, but this will not 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

+5
source share
2 answers

You can make the directive the validator itself. This way you can use 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 }; } } 
+3
source

you can modify an existing function and add a tool to the closure, you can also add it to your own validator class (and, for example, write the 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 an argument (e.g. 100) to the validation function:

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

Source: https://habr.com/ru/post/1258197/


All Articles