In my page I am having a simple form group. in which I have to write a custom validation for a name.
this.searchForm = this._formBuilder.group({
profileName: new FormControl('', Validators.compose([Validators.required])),
TypeId: new FormControl('', Validators.compose([Validators.required])),
tempRange: new FormControl('', Validators.compose([Validators.required])),
region: new FormControl('', Validators.compose([Validators.required])),
quarter1: new FormControl('', Validators.compose([Validators.required])),
quarter2: new FormControl('', Validators.compose([Validators.required]))
}, {
validator: this.customValidator// your validation method
});
I have put the custom validation in a method this.customValidator .
One of my validation is to check duplicate check for profileName.
I am having issue on getting other method (where validation logic resides) in the same type script class from the validation method, when I am calling that method (which is not static or a function) I am getting an error as (on pressing f12)
ERROR Error: Uncaught (in promise): TypeError: this.validateProfileName is not a function... '.
Is there any way to call the particular method, or I need to implement all the logic in side the validation method it self.
Also how can I show the validation error message from there in the same style as the required field validation error message.
My validation method
customValidator(control: AbstractControl) {
debugger;
let profileName = control.get('profileName').value;
let retgionCode = control.get('regionCode').value;
let forcastType = control.get('forecastTypeId');
var status = this.validateProfileName(retgionCode, profileName);
if (!status)
control.get("profileName").setErrors({ 'invalidProfileName': true });
return null;
}
The problem is with this
. As you are having it now, you are loosing the scope of this
. Inside your custom validator, this
is not pointing to your component scope, but the function scope. And there is no validateProfileName
in the scope of the function, so Angular is giving you the correct error.
To preserve the context of this
, bind it:
validator: this.customValidator.bind(this)
Now you have access to the scope outside of the custom validator.