日期验证问题

Date validation issue

我在验证日期格式时遇到问题: 如果我写“01/01-1987”我需要验证为错误格式,它应该只接受“01/01/1987”|| “01-01-1987” || “01 01 1987”。我怎样才能做到这一点? 我有以下代码:

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);
    })

您可以再添加 1 个无效日期测试方法,例如:

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'))