Angular 2 Pass parameter to a validator function
Just move it to a class
class NpiNumValicator {
constructor(private someField: someType) {}
npiNumValidator(control: Control): { [s: string]: boolean } {
if (isNaN(control.value)) {
return { npiNAN: true };
}
}
}
then use it like
this.clientForm = _fb.group({ 'name': ['',
Validators.compose([Validators.required])], 'npi': ['',
Validators.compose([Validators.required,
new NpiNumValidator(someArg).npiNumValidator,
Validators.maxLength(10), Validators.minLength(10)
])
]});
to be able to use this
within npiNumValidator
you can use
var npiNumVal = new NpiNumValidator(someArg);
this.clientForm = _fb.group({ 'name': ['',
Validators.compose([Validators.required])], 'npi': ['',
Validators.compose([Validators.required,
npiNumVal.npiNumValidator.bind(npiNumVal),
Validators.maxLength(10), Validators.minLength(10)
])
]});
You also leverage a method of your component to create the validation function. This way you will be able to access properties of this component using an arrow function.
Here is a sample:
@Component({ ... })
export class MyComponent {
constructor(private fb:FormBuilder) {
this.form = this.fb.group({
fieldName: [ '', this.createValidator() ]
});
}
createValidator() {
return (control) => {
var arr = this.arr;
(...)
};
}
}
Is it possible to add parameters to the function calls inside of the "compose" function?
Validator Declaration: straight out of Angular Code
/* Validator that requires controls to have a value of a minimum length. */
static minLength(minLength: number): ValidatorFn {
return (control: modelModule.AbstractControl): {[key: string]: any} => {
if (isPresent(Validators.required(control))) return null;
var v: string = control.value;
return v.length < minLength ?
{"minlength": {"requiredLength": minLength, "actualLength": v.length}} :
null;
};
}
Usage:
Validators.compose([Validators.minLength(4)]
NOTE: to understand it better, see How do JavaScript closures work?