Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unhandled edge case for isValid() function. #6229

Open
Niluk98 opened this issue Apr 17, 2024 · 1 comment
Open

Unhandled edge case for isValid() function. #6229

Niluk98 opened this issue Apr 17, 2024 · 1 comment

Comments

@Niluk98
Copy link

Niluk98 commented Apr 17, 2024

Describe the bug
I was using moment in my project. I wanted to use a if-condition that will execute a peice of code based on a condition that If the date string that I am getting is a valid date string then only it will proceed else it won't. But somehow the date string was coming undefined. Surprisingly, moment(undefined).isValid() was returning true. It should return false

To Reproduce
Steps to reproduce the behavior:
Just code this line : console.log(moment(undefined).isValid()); //output TRUE

Expected behavior
Output should be false.

Desktop (please complete the following information):

  • OS: ubuntu
  • Browser firefox

Moment-specific environment

  • The time zone setting of the machine the code is running on
  • The time and date at which the code was run
  • Other libraries in use (TypeScript, Immutable.js, etc)

Please run the following code in your environment and include the output:

console.log((new Date()).toString())
console.log((new Date()).toLocaleString())
console.log((new Date()).getTimezoneOffset())
console.log(navigator.userAgent)
console.log(moment.version)

Screenshot from 2024-04-17 13-21-48

Additional context
Add any other context about the problem here.

@antarilos
Copy link

The point is that moment(undefined) is the same as moment(), so in both statements a Moment object with the current time and date is returned.

I would suggest, assuming your date string is stored in myStringDate variable, to use:

if (myStringDate && moment(myStringDate).isValid()) {
  // Do whatever is needed when the date is valid
}

Just in case you would prefer an early return pattern:

if (!myStringDate || !moment(myStringDate).isValid()) {
  return;
}
// Do whatever is needed when the date is valid

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants