formio / formio.js

JavaScript powered Forms with JSON Form Builder
https://formio.github.io/formio.js
MIT License
1.86k stars 1.05k forks source link

Issues with validating date field with format 'dd-MM-yyyy' #5456

Closed flinden68 closed 5 months ago

flinden68 commented 7 months ago

Currently we are facing a problem with the validation of a date field after we upgraded formiojs from 4.13.5 to 4.17.2

In the builder with have a date field with format set to dd-MM-yyyy, it is our European date format.

When we load the form and add 13-12-2001 in the date field, the validation fails, but 12-12-2001 will pass the validation. So our suspicion is that the US date format is used during validation.

When we compare date validation in de Validator, see https://github.com/formio/formio.js/blob/master/src/validator/Validator.js, we noticed an extra check in the 4.17.2

4.17.2 version

check(component, setting, value) {
          if (!value) {
            return true;
          }
          if (value === 'Invalid date' || value === 'Invalid Date') {
            return false;
          }
          if (typeof value === 'string') {
            value = new Date(value);
          }
          return value instanceof Date === true && value.toString() !== 'Invalid Date';
        }

older version

check(component, setting, value) {
          if (!value) {
            return true;
          }
          if (value === 'Invalid date' || value === 'Invalid Date') {
            return false;
          }
          return value instanceof Date === true && value.toString() !== 'Invalid Date';
        }

And we see it fails on the line

value = new Date(value);

How can we validate correctly our date field with format dd-MM-yyyy????

le3bl commented 7 months ago

In the newer version of Form.io you're using, the date validation logic includes a line that converts the value to a Date object (value = new Date(value);). However, JavaScript's Date() constructor can be problematic with non-US date formats. If you pass a date in the DD/MM/YYYY format, the constructor might return an 'Invalid Date' object, as JavaScript primarily expects the YYYY/MM/DD or MM/DD/YYYY formats.

To work around this, you could preprocess the date string to convert it into a format that JavaScript's Date() constructor can recognize. This involves splitting the date string and rearranging it into a supported format. For example, you could split a DD/MM/YYYY formatted string and rearrange it to YYYY/MM/DD before passing it to the Date() constructor.

Alternatively, you could explore using a custom validation function that handles European date formats more gracefully. This might involve manually parsing the date string and checking its validity against your specific format requirements.

flinden68 commented 7 months ago

Thanks, we have found a way to use a custom validator

daneformio commented 5 months ago

Closing this issue as resolved.