Reputation: 1372
How can I implement my custom Validator in Angular 2?
I found this plunker:
constructor(private fb: FormBuilder) {
this.form = fb.group({
'singleSelection': ['Rio', [App.validateCity]] // initial value as string
'multipleSelection': [['Red','Blue'], [App.validateColor]] // initial value as array
});
}
static validateCity(c: FormControl) {
if (c.value !== 'New York') {
return { citySucks: true };
}
return null;
}
static validateColor(c: FormControl) {
if (c.value.indexOf('Green') < 0) {
return {badColor: true};
}
return null;
}
But, I think it would be better to implement an interface Validator, like class MinLengthValidator
. But, I don't know how to use it!
Upvotes: 1
Views: 981
Reputation: 3618
// Control handling
this.form = fb.group({
'singleSelection': ['Rio', this.text({min: 10})]
});
// Text function to handle min value
public static text(config = {}): ValidatorFn {
return (control: Control): {} => {
if(!control) {
return null;
}
let c: string = control.value;
if(config.min) {
if(c.length < config.min) {
return {
"This field must have at least " + config.min + " characters."
};
}
}
}}
Upvotes: 1