casbloem / vue-luxon

Easy use of datetime with Luxon in Vue
https://npmjs.com/package/vue-luxon
72 stars 8 forks source link

Access to .isValid property? #24

Open timblack1-WC opened 2 years ago

timblack1-WC commented 2 years ago

Plain luxon DateTime objects provide a boolean .isValid property indicating whether the input date is a valid date. What is a good way to find out if the input date is valid with vue-luxon?

Here's the solution I came up with. this.$luxon() either returns a formatted date or throws an error when the input date is invalid or unparseable. So instead of using an if() condition to test for the .isValid property, I used a try...catch block which tries to parse the input date, and catches the error thrown if the date could not be parsed or is invalid.

The example below uses nested try...catch blocks to demonstrate how it is possible to validate multiple input formats, which is what my code needed to do.

         this.errorMessage = ''
-        this.invalidDate = false
-        if (DateTime.fromFormat(val, 'MM/dd/yyyy').isValid) {
-          this.date = DateTime.fromFormat(val, 'MM/dd/yyyy').toFormat(
-            'yyyy-MM-dd'
-          )
-          this.invalidDate = false
-        } else if (DateTime.fromFormat(val, 'M/d/yyyy').isValid) {
-          this.date = DateTime.fromFormat(val, 'M/d/yyyy').toFormat(
-            'yyyy-MM-dd'
-          )
-          this.invalidDate = false
-        } else if (DateTime.fromFormat(val, 'MMddyyyy').isValid) {
-          this.date = DateTime.fromFormat(val, 'MMddyyyy').toFormat(
-            'yyyy-MM-dd'
-          )
-          this.invalidDate = false
-        } else {
-          this.invalidDate = true
+        try {
+          // Validate date
+          this.date = this.$luxon(val, {
+            input: { format: 'MM/dd/yyyy', zone: 'local' },
+            output: { format: 'yyyy-MM-dd', zone: 'local' },
+          })
+        } catch (e) {
+          try {
+            // Convert date format
+            this.date = this.$luxon(val, {
+              input: { format: 'M/d/yyyy', zone: 'local' },
+              output: { format: 'yyyy-MM-dd', zone: 'local' },
+            })
+          } catch (e) {
+            try {
+              // Convert date format
+              this.date = this.$luxon(val, {
+                input: { format: 'MMddyyyy', zone: 'local' },
+                output: { format: 'yyyy-MM-dd', zone: 'local' },
+              })
+            } catch (e) {
+              this.errorMessage = 'Please enter a valid date'
+            }
+          }
         }

Is there a better way to accomplish this same goal with vue-luxon?