I am attempting to attach a custom validator to an Angular Form Control. I am initializing the Form Controls in the ngOnInit method. This validator should check that the field has been given an input (much like Validators.required), but only if a boolean class member this.shouldCheck
is true.
However, when I attempt to access that class member from the validator function, it cannot find the instance of this
. I know there are some notorious scoping issues with this
in Js, but I thought that was solved with Typescript. Not sure how I can check that boolean in the validator.
My component.ts:
// this shouldCheck's value is bound to a checkbox on the form
private shouldCheck: boolean = false;
constructor(private formBuilder: FormBuilder) {}
ngOnInit() {
this.employeeCreateForm = this.formBuilder.group({
firstName: [null, [
this.myRequiredValidator,
Validators.maxLength(30),
Validators.pattern('[^<|]+$')]],
lastName: [null, [
this.myRequiredValidator,
Validators.maxLength(40),
Validators.pattern('[^<|]+$')]]
}
My custom validator:
myRequiredValidator(control: AbstractControl): ValidationErrors | null {
// if shouldCheck, perform a basic "required field" validation
if (this.shouldCheck) {
return !!control.value ? null : {required: true};
}
// else, don't apply validation error
return null;
}
No matter where I initialize shouldCheck
, the validator function can't resolve this
and thus cannot even instantiate the FormGroup.
I tried using a simple null check:
if (this && this.shouldCheck) {
// do validation
}
...which allows the FormGroup to be constructed but it never seems to be able to resolve the this
, even after the form has been initialized. I know ngOnInit runs after the class constructor so that shouldn't have been the issue anyway, but that's all I could think to try.
Thanks.
nameRequiredValidator = (control: AbstractControl): ValidationErrors | null => {
// if shouldCheck, perform a basic "required field" validation
if (this.shouldCheck) {
return !!control.value ? null : {required: true};
}
// else, don't apply validation error
return null;
}
Or
ngOnInit() {
this.employeeCreateForm = this.formBuilder.group({
firstName: [null, [
this.myRequiredValidator(),
Validators.maxLength(30),
Validators.pattern('[^<|]+$')]],
lastName: [null, [
this.myRequiredValidator(),
Validators.maxLength(40),
Validators.pattern('[^<|]+$')]]
}
myRequiredValidator(): (AbstractControl) => ValidationErrors | null {
return (control: AbstractControl): ValidationErrors | null => {
// if shouldCheck, perform a basic "required field" validation
if (this.shouldCheck) {
return !!control.value ? null : {required: true};
}
// else, don't apply validation error
return null;
};
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.