如何在express-validator的checkSchema中实现出生日期验证?
Hey there! I see you're having trouble validating a yyyy/mm/dd formatted birth date using express-validator's checkSchema—let's get this sorted out.
The main issue with your current code is that the isISO8601 validator expects dates in the standard yyyy-mm-dd format (ISO 8601), not the slash-separated yyyy/mm/dd you're working with. Here's a revised schema that properly handles your date format while keeping your before/after range checks:
import { checkSchema } from 'express-validator'; export const validator = { editAction: checkSchema({ date: { custom: { options: (value) => { // First, validate the input matches yyyy/mm/dd format const datePattern = /^\d{4}\/\d{2}\/\d{2}$/; if (!datePattern.test(value)) { throw new Error('Date of birth must be in yyyy/mm/dd format'); } // Split the date and create a Date object (note: months are 0-indexed) const [year, month, day] = value.split('/').map(Number); const birthDate = new Date(year, month - 1, day); // Verify the date is valid (prevents invalid dates like 2023/02/31) if ( birthDate.getFullYear() !== year || birthDate.getMonth() !== month - 1 || birthDate.getDate() !== day ) { throw new Error('Date of birth is not a valid date'); } return true; }, errorMessage: 'Invalid date format or date value' }, isBefore: { options: '2008-01-01', // Use ISO 8601 format for the comparison date errorMessage: 'Date of birth should be before 01-01-2008' }, isAfter: { options: '1920-01-01', errorMessage: 'Date of birth should be after 01-01-1920' } } }) };
Let's break down what's happening here:
- Custom Format Validation: We use a regex to ensure the input strictly follows
yyyy/mm/dd(two digits for month and day). - Valid Date Check: Converting the input to a
Dateobject and cross-checking the values ensures we don't accept invalid dates (like February 31st). - Range Checks: The
isBeforeandisAftervalidators work perfectly with ISO 8601 formatted dates (yyyy-mm-dd) for the comparison values, so we just adjust those to match the expected format.
Alternatively, if you prefer using built-in validators instead of a custom one, you can use isDate with a format option (note: this relies on validator.js's date parsing, which supports format strings):
date: { isDate: { options: { format: 'YYYY/MM/DD' }, errorMessage: 'Date of birth must be a valid date in yyyy/mm/dd format' }, isBefore: { options: '2008-01-01', errorMessage: 'Date of birth should be before 01-01-2008' }, isAfter: { options: '1920-01-01', errorMessage: 'Date of birth should be after 01-01-1920' } }
This built-in approach is simpler, but the custom validator gives you more control if you need to add edge-case checks later.
内容的提问来源于stack exchange,提问作者André Bottentuit

