npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

expressjs-field-validator

v3.0.6

Published

Plugin for validating field values of json request in expressjs

Downloads

53

Readme

expressjs-field-validator

Request field validator for expressjs

Reliability Rating Bugs code_smells coverage duplicated_lines_density ncloc sqale_rating alert_status security_rating security_rating sqale_index vulnerabilities

Installation

$ npm install expressjs-field-validator

How To Use

 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

});

Getting Started

Defining a Field

Use param(<field Name>) to define a field. It should end with end()

param('userName').isRequired().end()

Defines a field userName which is mandatory.

Available Options

isRequired()

Field is mandatory

isArray()

Expects array

isObject()

Expects object

isNumber()

Expects number

isEmail()

Expects email

isBoolean()

Expects boolean value

isDate()

Expects a date with default format YYYY-MM-DD

dateFormat(format)
  • 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
minimumNumber(min)
  • min Mandatory Number Expects number and must be greater than or equal to min
maximumNumber(max)
  • max Mandatory Number Expects number and must be less than or equal to max
minimumLength(min)
  • min Mandatory Number Expects number/string and length must be less than or equal to min
maximumLength(max)
  • max Mandatory Number Expects number/string and length must be less than or equal to max
shouldInclude(inclues)
  • inclues Mandatory Array Expects number/string and must be one of given array includes
shouldExclude(excludes)
  • excludes Mandatory Array Expects number/string and must not be one of given array excludes
isMobileNumberWithCountryCode(countryCode)
  • countryCode Mandatory String Expects mobile number with or without countryCode
isMobileNumberWithCountryCodeMandatory()

Expects mobile number which should starts with the country code set with isMobileNumberWithCountryCode

isMobileNumberWithMinimumLength(min)
  • min Mandatory Number Minimum length of mobile number without country code
isMobileNumberWithMaximumLength(max)
  • max Mandatory Number Maximum length of mobile number without country code
customValidator(function)
  • function Mandatory Function A function with arguments (value, req, error) value is the value of the field req request object error function with takes error message, should be called on error
(value, req, error) => {
  if (value !== 100) {
    error('Invalid value customValidator');
  }
}
addChild(child)
  • child Mandatory field definition object Add a child object for arrays and objects
addChildren(children)
  • children Mandatory Array of field definition objects Add a list of children objects for arrays and objects
sendErrorMessage(message)
  • 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>"
        }
    ]
}
end() :bangbang::bangbang: Mandatory

Ends a param definition

Creating a validation middleware

  • validateBody() Validate body
  • validateParam() Validate param
  • validateQuery() Validate query
  • validateHeader() Validate header

Available Options

isToBeRejected()

Defines the validation failure event - Server returns http status code set via sendErrorCode (default 422), :heavy_exclamation_mark: will not proceed to the next middleware Response body

{
    "error": [
        {
            "location": "body.sort",
            "param": "sort",
            "message": "Invalid Field Error"
        }
    ]
}
isToBeForwarded()

Defines the validation failure event - Error is set to request.locals.data and error code to request.locals.statusCode, :white_check_mark: will proceed to the next middleware Error object Response body

{
    "error": [
        {
            "location": "body.sort",
            "param": "sort",
            "message": "Invalid Field Error"
        }
    ]
}
checkService
  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 
  
});
skipService

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 
  
});
sendErrorCode(errorCode)
  • errorCode Mandatory Error code which should be rejected
debug(isDebugEnabled)
  • isDebugEnabled Mandatory Pass true 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
        }
    ]
}
addParams(paramList)
  • 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

done() :bangbang::bangbang: Mandatory

Ends a validation definition

Dealing with nested objects

Request body

{
  "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

Validation

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

});