moment / luxon

⏱ A library for working with dates and times in JS
https://moment.github.io/luxon
MIT License
15.23k stars 730 forks source link

Ability to validate an input string according to format. #1479

Open moltar opened 1 year ago

moltar commented 1 year ago

Is your feature request related to a problem? Please describe.

When using a throwOnInvalid setting, it becomes challenging to validate provided string dates according to a format pattern.

Describe the solution you'd like

Have an option (third positional) that will allow invalid dates to be set, which then in turn will go thru the existing path and set the isValid prop on the object.

This option could be named throwOnInvalid and always default to the global value of the Settings.throwOnInvalid, and would allow the user to override the value on per case-by-case basis.

// global is to throw
Settings.throwOnInvalid = true

DateTime
  .fromFormat(formatedDate, format, {
    // override local not to throw
    throwOnInvalid: false
  })
  .isValid

And/or:

Have a static method DateTime.isValid (maybe with a better name).

Describe alternatives you've considered

Wrap into try/catch block just to check if the format is correct.

try {
  return DateTime.fromFormat(formatedDate, format)
} catch {
  return
}

Additional context

N/A

icambron commented 1 year ago

Another option is to add more information to fromFormatExplain so that you could check validity more easily with it.