vue-luxon icon indicating copy to clipboard operation
vue-luxon copied to clipboard

Access to .isValid property?

Open timblack1-WC opened this issue 2 years ago • 0 comments

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?

timblack1-WC avatar Jun 28 '22 16:06 timblack1-WC