Search code examples
javascriptreactjsdate-fns

Date validation issue


I have an issue validating Date format: If I write "01/01-1987" I need to validate as a wrong format, it should only accept "01/01/1987" || "01-01-1987" || "01 01 1987". How can I achieve this? I have the following code:

dateOfBirth: yup
    .string()
    .required(DOB_EMPTY_FIELD)
    .test('invalid-length', DOB_ERROR, value => value.length === 10)
    .test('invalid-date', DOB_ERROR, value => {
      function compareFutureDate(date) {
        return isBefore(
          parse(
            date.replace(/[\/ ]/g, '-'),
            DATE_OF_BIRTH_VALUES.dateFormat,
            new Date()
          ),
          sub(new Date(), { days: 1 })
        );
      }

      function comparePastDate(date) {
        return isAfter(
          parse(
            date.replace(/[\/ ]/g, '-'),
            DATE_OF_BIRTH_VALUES.dateFormat,
            new Date()
          ),
          new Date('12-31-1900')
        );
      }

      return compareFutureDate(value) && comparePastDate(value);
    })

Solution

  • You can add 1 more test method for invalid date, like this one:

    const isValidFormat = str => str.replace(/[^\/ -]/g, "")
                                    .split('')
                                    .every((e, _, a) => a[0] === e)
    
    console.log('12-12-1994:', isValidFormat('12-12-1994'))
    console.log('12/12-1994:', isValidFormat('12/12-1994'))
    console.log('12-12 1994:', isValidFormat('12-12 1994'))
    console.log('12/12/1994:', isValidFormat('12/12/1994'))