问题描述
我在验证日期格式时遇到问题: 如果我写“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',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,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'))