Custom validation rules help you check user input in ways built-in checks can't. This keeps your app safe and working right.
0
0
Custom validation rules in Express
Introduction
You want to check if a username is unique before saving.
You need to verify a password meets special rules like including symbols.
You want to confirm a date is not in the past.
You want to validate a custom ID format that built-in validators don't support.
Syntax
Express
const { body, validationResult } = require('express-validator');
app.post('/route', [
body('fieldName').custom(value => {
if (!yourCheck(value)) {
throw new Error('Custom error message');
}
return true;
})
], (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
res.send('Success');
});The custom method takes a function that returns true if valid or throws an error if invalid.
Always return true when validation passes to signal success.
Examples
This checks if the age is 18 or older.
Express
body('age').custom(value => { if (value < 18) { throw new Error('Must be at least 18'); } return true; })
This example shows an async check to see if a username is already used.
Express
body('username').custom(async value => { const userExists = await checkUserInDatabase(value); if (userExists) { throw new Error('Username already taken'); } return true; })
Sample Program
This Express app has a route '/register' that checks if the password includes at least one number. If not, it sends an error. Otherwise, it confirms success.
Express
const express = require('express'); const { body, validationResult } = require('express-validator'); const app = express(); app.use(express.json()); // Custom validation to check if password has a number app.post('/register', [ body('password').custom(value => { if (!/\d/.test(value)) { throw new Error('Password must contain a number'); } return true; }) ], (req, res) => { const errors = validationResult(req); if (!errors.isEmpty()) { return res.status(400).json({ errors: errors.array() }); } res.send('Registration successful'); }); app.listen(3000);
OutputSuccess
Important Notes
Custom validators can be synchronous or asynchronous (return a promise).
Always handle validation errors by checking validationResult(req).
Use clear error messages to help users fix input mistakes.
Summary
Custom validation rules let you check inputs beyond built-in checks.
Use custom() with a function that throws errors on invalid input.
Always return true when validation passes.