An express.js middleware for input validation.
Securing your API
s by validating the inputs.
express-input-validation is simple yet powerful node module that makes your API robust and discard any request with invalid input.
npm install express-input-validation
OR
yarn add express-input-validation
you can ask express-input-validation
to get value from any of these(following list) using from
key in rules array,
- Header (header)
- Query (query)
- Body (body)
- Params (param)
and can pass any custom validation function using validation_function
in the rules array. Also you can pass a message
in rules for particular rule or it'll be default send a invalid ${key_name}
as message.
Following are the example for validating using express-input-validation
, here I have included all four type of inputs that most commonly an API can have:
{
"from": "query",
"key": "emailId",
validation_function: value => value.indexOf("@") > -1,
"datatype": "number",
"is_optional": true
}
In rules array the above one can be one of the objects, here I've showed a custom validation_function
without message, this ll return Invalid emailId
incase the email id is not found or if it doesn't have an @
in the value string.
Now new rule can be defined as is_optional, where if its declared as optional, only if the field value found then it'll be validated otherwise it'll be ignored.
In the rule you can also specify a datatype in datatype
key to check for specific datatype of the value. datatypes can be checked below.
Datatype | Description | Alternative key |
---|---|---|
number |
checks if its a valid number | num , int , integer |
string |
checks if typeof is string and first character is not a numeric | str |
float |
checks if its a number and has a decimal value | - |
object |
checks if a object | obj |
alphanumeric |
checks if value has atleast one character and number | - |
only-alpha |
checks if value has only alphabets | - |
key
,from
are required keys in object in all of the rule you define.- a rule without a
validation_function
is considered to be onlyrequired
field, i.e.,express-input-validation
only checks if there is a field in specifiedfrom
key in the object. - Datatype is still experimential.
- Documentation for
Getting Started
- More DataType checks and
datetime
checks(minor). - Code Optimization.
- Build passing badge after creating test cases.
MIT License