Andrew Graham-Yooll Andrew Graham-Yooll - 3 months ago 9
AngularJS Question

Custom Validators- Passing an Argument

I have followed Josh Moroney's tutorial on creating a custom validator. I got it working, being able to call

newForm.ts

new FormControl(question || '',
Validators.compose([AgeValidator.ageIsValid])
);


AgeValidator.ts

interface ValidationResult {
[key:string]:any;
}

export class AgeValidator {
static ageIsValid(control: AbstractControl): ValidationResult{

console.log('this is control', control)
console.log('this is control.value', control.value)

if(isNaN(control.value)){

return {
"notValid": true,
"message": "this is not a number"
};
}
if(control.value % 1 !== 0){
return {
"notValid": true,
"message": "cant be zero"
};
}

if(control.value < 18){
return {
"notValid": true,
"message": "cant be less than 18"
};
}
if(control.value > 120){
return {
"notValid": true,
"message": "Must be less than 120"
};
}
else{
return null
}

}


}

Is it possible to add an argument into .ageIsValid method, such that I can specify the age that is valid? For example,

new FormControl(question || '',
Validators.compose([AgeValidator.ageIsValid(18)])
);


What I have tried:

1) Getting rid of
static
and using .ageIsValid like anyother method. Result: TS Error

2) Passing an argument like above. Result: Error

Anything else I can try?

Answer

You can use a class with an instance method (instead of static)

class AgeValidator {
  constructor(private someParam) {}
  ageIsValid(control: AbstractControl): ValidationResult {
    // use someParam here
  }
}
var ageValidator = new AgeValidator('foo')
new FormControl(question || '', 
    Validators.compose([ageIsValid.ageIsValid.bind(ageValidator)])
);

or a function that returns a function

static ageIsValid (someParam) {
  return (control: AbstractControl): ValidationResult => {
    // use someParam here
  }
}
new FormControl(question || '', 
    Validators.compose([ageIsValid('foo')])
);
Comments