简体   繁体   中英

Date validation using joi - invalid date isn't throwing an error 2019-11-31

I am trying to use JOI to check that a date is a valid date and also not in the future. I would expect 31 November 2001 to fail because there is no 31 November.. however it it passes!

Strangely 32 November 2001 fails? Any idea what the problem is? My test code is below

const joi = require('joi')
const moment = require('moment')

const schema = joi.object({
    location: joi.string().strict().trim().min(1).required().error(() => {
        return {
            message: 'A location must be entered',
        }
    }),
    incidentDate: joi.date().max(moment().format('YYYY-MM-DD')).required().error(() => {
        return {
            message: 'A date must be entered that is not in the future',
        }
    }),

})

const requestForm = {"dateOfIncident":{"day":"31","month":"11","year":"2001"},"location":"sdcds"}
const strDate   = `${requestForm.dateOfIncident.year}-${requestForm.dateOfIncident.month}-${requestForm.dateOfIncident.day}`

requestForm.incidentDate = strDate

const joiErrors = joi.validate(requestForm, schema, { stripUnknown: true })

console.log(joiErrors)

adding another .format did the trick

incidentDate: joi.date().format('YYYY-MM-DD').max(moment().format('YYYY-MM-DD')).required().error(() => {
        return {
            message: 'A date must be entered in the correct format that is not in the future',
        }
    })

For anyone coming later, I manage to validate the 31ths as follows:

const myDate = Joi.alternatives().conditional('myDate', {
    is: Joi.date().iso(),
    then: Joi.string().regex(/^((?!(([0-9]{4}-02-30|[0-9]{4}-02-31|[0-9]{4}-04-31|[0-9]{4}-06-31|[0-9]{4}-09-31|[0-9]{4}-11-31)(T[0-9]{2}:[0-9]{2}:[0-9]{2}Z)?)).)*$/)
    .message('Date does not exist.'),
    otherwise: Joi.string().regex(/^(?!.)/).message('Date is not in a valid format')
})

The otherwise regex is just for allowing a custom message, otherwise it would only say that none of the alternatives were fulfilled.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM