Validate Input
Last updated
Was this helpful?
Last updated
Was this helpful?
Let's see how to validate any data coming in as input in your Express endpoints.
Say you have a POST endpoint that accepts the name, email, and age parameters:
How do you perform server-side validation on those results to make sure that:
name is a string of at least 3 characters?
email is a real email?
age is a number, between 0 and 110?
The best way to handle validation on any kind of input coming from outside in Express is by using the :
You require the check
and validationResult
objects from the package:
We pass an array of check()
calls as the second argument of the post()
call. Every check()
call accepts the parameter name as argument. Then we call validationResult()
to verify there were no validation errors. If there are any, we tell them to the client:
Notice I used:
isLength()
isEmail()
isNumeric()
contains()
, checks if value contains the specified value
equals()
, checks if value equals the specified value
isAlpha()
isAlphanumeric()
isAscii()
isBase64()
isBoolean()
isCurrency()
isDecimal()
isEmpty()
isFQDN()
, checks if it's a fully qualified domain name
isFloat()
isHash()
isHexColor()
isIP()
isIn()
, checks if the value is in an array of allowed values
isInt()
isJSON()
isLatLong()
isLength()
isLowercase()
isMobilePhone()
isNumeric()
isPostalCode()
isURL()
isUppercase()
isWhitelisted()
, checks the input against a whitelist of allowed characters
You can validate the input against a regular expression using matches()
.
Dates can be checked using:
isAfter()
, checks if the entered date is after the one you pass
isBefore()
, checks if the entered date is before the one you pass
isISO8601()
isRFC3339()
All those checks can be combined by piping them:
If there is any error, the server automatically sends a response to communicate the error. For example if the email is not valid, this is what will be returned:
This default error can be overridden for each check you perform, using withMessage()
:
What if you want to write your own special, custom validator? You can use the custom
validator.
In the callback function you can reject the validation either by throwing an exception, or by returning a rejected promise:
The custom validator:
can be rewritten like this:
There are many more of these methods, all coming from , including:
For exact details on how to use those validators, .