Request field validator for expressjs
- Installation
- How To Use
- Getting Started
- Defining a Field
- Available Options
- isRequired()
- isArray()
- isObject()
- isNumber()
- isEmail()
- isBoolean()
- isDate()
- dateFormat(format)
- minimumNumber(min)
- maximumNumber(max)
- minimumLength(min)
- maximumLength(max)
- shouldInclude(inclues)
- shouldExclude(excludes)
- isMobileNumberWithCountryCode(countryCode)
- isMobileNumberWithCountryCodeMandatory()
- isMobileNumberWithMinimumLength(min)
- isMobileNumberWithMaximumLength(max)
- addChild(child)
- addChildren(children)
- sendErrorMessage(message)
- end()
‼️ ‼️ Mandatory
- Available Options
- Creating a validation middleware
- Defining a Field
- Dealing with nested objects
$ npm install expressjs-field-validator
const {
validateBody,
validateParam,
validateQuery,
param,
} = require('expressjs-field-validator');
router.post('/users/:id',
validateParam().addParams([
param('id').isNumber().end()
]).done(),
validateBody().addParams([
param('userId').isNumber().end()
]).done(),
validateQuery().addParams([
param('userName').isRequired().end()
]).done(),
validateHeader().addParams([
param('Authorization').isRequired().end()
]).done(),
(req, res, next) => {
// Main Service Here
});
Use param(<field Name>)
to define a field. It should end with end()
param('userName').isRequired().end()
Defines a field userName
which is mandatory.
Field is mandatory
Expects array
Expects object
Expects number
Expects email
Expects boolean value
Expects a date with default format YYYY-MM-DD
format
Mandatory String specify date format, supported
YYYY-MM-DD
DD-MM-YYYY
MM-DD-YYYY
YYYY/MM/DD
DD/MM/YYYY
MM/DD/YYYY
min
Mandatory Number Expects number and must be greater than or equal tomin
max
Mandatory Number Expects number and must be less than or equal tomax
min
Mandatory Number Expects number/string and length must be less than or equal tomin
max
Mandatory Number Expects number/string and length must be less than or equal tomax
inclues
Mandatory Array Expects number/string and must be one of given arrayincludes
excludes
Mandatory Array Expects number/string and must not be one of given arrayexcludes
countryCode
Mandatory String Expects mobile number with or withoutcountryCode
Expects mobile number which should starts with the country code set with isMobileNumberWithCountryCode
min
Mandatory Number Minimum length of mobile number without country code
max
Mandatory Number Maximum length of mobile number without country code
function
Mandatory Function A function with arguments (value
,req
,error
)value
is the value of the fieldreq
request objecterror
function with takes error message, should be called on error
(value, req, error) => {
if (value !== 100) {
error('Invalid value customValidator');
}
}
child
Mandatory field definition object Add a child object for arrays and objects
children
Mandatory Array of field definition objects Add a list of children objects for arrays and objects
message
Mandatory String Custom message to be send back in case of validation failure
// Default message
{
"error": [
{
"location": "body.sort",
"param": "sort",
"message": "Invalid Field Error"
}
]
}
// Custom message
{
"error": [
{
"location": "body.sort",
"param": "sort",
"message": "<Your Custom Error Message>"
}
]
}
Ends a param definition
validateBody()
Validate bodyvalidateParam()
Validate paramvalidateQuery()
Validate queryvalidateHeader()
Validate header
Defines the validation failure event - Server returns http status code set via sendErrorCode
(default 422), ❗ will not proceed to the next middleware
Response body
{
"error": [
{
"location": "body.sort",
"param": "sort",
"message": "Invalid Field Error"
}
]
}
Defines the validation failure event - Error is set to request.locals.data
and error code to request.locals.statusCode
, ✅ will proceed to the next middleware
Error object
Response body
{
"error": [
{
"location": "body.sort",
"param": "sort",
"message": "Invalid Field Error"
}
]
}
const { checkService } = require('expressjs-field-validator');
Pass middleware to checkService
, which must be skipped if isToBeForwarded
enabled and validation errors are found
router.get('/users/:id',
validateBody().isToBeForwarded().sendErrorCode(500).debug(false).addParams([
param('id').isRequired().isNumber().end()
]).done(),
checkService((req, res, next) => {
// This middleware is skipped if id is empty or not a number
}),
(req, res, next) => {
// This middleware Will not be skipped, error data will be availble here - req.locals.data and status code - request.locals.statusCode here
});
manually invoke forward mode, if this is set from any middleware, the middlewares wrapped inside checkService
won't be executed
const { skipService } = require('expressjs-field-validator');
router.get('/users/:id',
(req, res, next) => {
skipService(req, 'SOME-ERROR');
next();
}),
checkService((req, res, next) => {
// This middleware is skipped
}),
(req, res, next) => {
// This middleware Will not be skipped, error data will be availble here - req.locals.data and status code - request.locals.statusCode here
});
errorCode
Mandatory Error code which should be rejected
isDebugEnabled
Mandatory Passtrue
for development environments, the error object will contain more details about error Error object
{
"error": [
{
"location": "body.sort",
"param": "sort",
"message": "Invalid Field Error :: somevalueforsort Must Be A Boolean" // More details on error
}
]
}
paramList
Mandatory Array of field definition objects
validateBody().addParams([
// Add List of definition here
param('field1').isRequired().end(),
]).done()
Definintion of a field here : Defining a Field
Ends a validation definition
{
"field1": "Value", // String, Mandatory
"field2": [ // array, Mandatory
{ "field21": "44443" }, // object Optional, number mandatory
{ "field21": "44443" }
],
"field3": { // Object Optional
"field31": "true", // Boolean Mandatory
"field32": "String" // String Mandatory
},
"field4": [ // array, Mandatory
123, 445, 3434 // Number Optional
],
}
Should send http status code 500 in case of error
router.post('/users/:id',
validateBody().isToBeRejected().sendErrorCode(500).addParams([
param('field1').isRequired().end(), // Use end() to end a definition
param('field2').isRequired().isArray().isRequired().addChild(
param('field2-array').isObject().addChild( // field2-array is for tracking, you can give any name here
param('field21').isNumber().isRequired().end()
).end()
).end(),
param('field3').isObject().addChildren([
param('field31').isBoolean().isRequired().end(),
param('field32').isRequired().end()
]).end(),
param('field4').isRequired().isArray().isRequired().addChild(
param('field4-array').isNumber().end()
).end(),
]).done(), // Use done() to end a validation
validateParam().isToBeRejected().sendErrorCode(500).addParams([
param('field1').isRequired().end(), // Use end() to end a definition
]).done(), // Use done() to end a validation
// define validateQuery(),
// define validateHeader(),
(req, res, next) => {
// Main Service Here
});