hussain
hussain

Reputation: 7123

How to assign function to object property in typescript?

I have simple use case where i want to validate date input it should be in the format "YYYY/MM/DD" if anything other format passed throw error so question how can i assign function to object property in typescript ?

main.ts

const ValidateRuless = [

    {element: "date", values: this.validateDate()}

];

function validateDate(date: string) {
    const date_regex =  /^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/ ;
    if (!(date_regex.test(date))) {
        return false;
    }
}

Upvotes: 2

Views: 2132

Answers (1)

Ryan Cavanaugh
Ryan Cavanaugh

Reputation: 221392

To call a function, don't use this.functionName. Only use this. when calling methods of classes.

You probably also want to return a value in both cases in validateDate

Example:

const ValidateRuless = [

    {element: "date", values: validateDate("2018/05/17")}

];

function validateDate(date: string) {
    const date_regex =  /^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/ ;
    if (!(date_regex.test(date))) {
        return false;
    } else {
        return true;
    }
}

Upvotes: 4

Related Questions