Reputation: 9184
I have such class:
export class GlobalValidation {
static emailPattern(control: AbstractControl): ValidationResult {
var EMAIL_REGEXP = Pattern.EMAIL;
return this.checkPattern(control, EMAIL_REGEXP);
}
static urlPattern(control: AbstractControl): ValidationResult {
var URL_REGEXP = Pattern.URL;
return this.checkPattern(control, URL_REGEXP);
}
static checkPattern(control: AbstractControl, pattern: any) {
if (control.value != "" && !pattern.test(control.value)) {
return {"incorrectPatternFormat": true};
}
return null;
}
}
EXCEPTION: Uncaught (in promise): Error: Error in :0:0 caused by: Cannot read property 'checkPattern' of undefined TypeError: Cannot read property 'checkPattern' of undefined at GlobalValidation.urlPattern
What am I doing wrong?
When I rewrite class to this:
export class GlobalValidation {
static emailPattern(control: AbstractControl): ValidationResult {
var EMAIL_REGEXP = Pattern.EMAIL;
if (control.value != "" && !URL_REGEXP.test(control.value)) {
return {"incorrectPatternFormat": true};
}
return null;
}
static urlPattern(control: AbstractControl): ValidationResult {
var URL_REGEXP = Pattern.URL;
if (control.value != "" && !URL_REGEXP.test(control.value)) {
return {"incorrectPatternFormat": true};
}
return null;
}
}
Everything is fine.
Seems that something is obvious, but I miss it.
Upvotes: 2
Views: 2834
Reputation: 5826
You can't access this
from static method. Using static classes has one purpose and that is - you don't need to create a new instance of the class to use the method.
You should use GlobalValidation.checkPatter(...)
as Phil Cap suggested or just rewrite it, so it doesn't use the properties of GlobalValidation class.
Upvotes: 2
Reputation: 209
You are calling checkPattern
using this
, albeit it being a static method. Call checkPattern
using GlobalValidation.checkPattern(...)
Upvotes: 3