Home > Software design >  Check if selected date is greater than yesterday Typescript React, momentjs
Check if selected date is greater than yesterday Typescript React, momentjs

Time:12-07

how can i check if date is greater than yesterday using typescript and momentjs?

Im also using validator, example:

isPin: {
    validator: (value: string) => value.length <= 6 && value.length >= 4,
    message: 'Please enter a pin with 4 to 6 numbers'
},

I would like to use validator with the date too.

I have tried:

isGreaterThanYesterday: {
    validator: (value: string) => value.toString() > moment().toString(),
    message: 'The date must be greater than yesterday'
}

But it does not work.

CodePudding user response:

You did not provide date format but I will assume it is 'YYYY-MM-DD', as it is standard html format. So, if you want to check if date is strictly greater than yesterday, you can do it like this (check if date is greater or equal today's date):

value >= moment().format('YYYY-MM-DD')

If you want to check if date is greater or equal than yesterday, you can do it like this:

value >= moment().subtract(1, 'days').format('YYYY-MM-DD')

CodePudding user response:

Assuming value is a valid date string of format 'YYYY-MM-DD', you can perform the following operation:

isGreaterThanYesterday: {
    validator: (value: string):boolean => moment(value, 'YYYY-MM-DD').isAfter(moment().subtract(1, 'days') ,
    message: 'The date must be greater than yesterday'
}

Note that you do not need toString on value since type is already a string.

  • Related