byCoder
byCoder

Reputation: 9184

Typescript: Static method return value

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

Answers (2)

Dawid Zbiński
Dawid Zbiński

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

Phil Cap
Phil Cap

Reputation: 209

You are calling checkPattern using this, albeit it being a static method. Call checkPattern using GlobalValidation.checkPattern(...)

Upvotes: 3

Related Questions