I'm developing a form using Angular2's FormBuilder with custom validation.
Problem: In customValidator I'm using this
to access the local object data
. I'm getting a undefined
error when the validation is executed.
It looks like the customValidator is executed in a different object and therefore changing the this
reference
Question: How can I pass a reference of this
to the customValidator?
export class Ast {
public data:any;
public myForm:FormGroup;
constructor(private _fb:FormBuilder) {
this.data = {foo: "bar"};
}
customValidator(c: FormControl) {
if (this.data.foo == "bar") { // This line crashes
// DO something
}
}
ngOnInit() {
this.myForm = this._fb.group({
some_field: ['', [<any>Validators.required], this.customValidator]
})
}
}
The validator function needs to return null if no errors were found in the field value, meaning that the value is valid.
In the end, a custom validator is just a function that returns either an error object or null .
Implementing the Validator Interface A Validator implementation must contain a constructor, a set of accessor methods for any attributes on the tag, and a validate method, which overrides the validate method of the Validator interface.
Using an arrow function, to make sure the function is bound to this:
some_field: ['', [<any>Validators.required], c => this.customValidator(c)]
The accepted answer didn't work for me in Angular 2.0 due to typing issues (casting an AbstractControl
to a FormControl
, I believe). The following, however, solved the problem quite nicely:
ngOnInit() {
this.myForm = this._fb.group({
some_field: ['', [<any>Validators.required], this.customValidator.bind(this)]
});
}
Using the .bind(this)
on the reference to the validator did the trick for me.
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