Neolithic Psychedelic Mushrooms

    expressjs-field-validator

    2.2.1 • Public • Published

    expressjs-field-validator

    Request field validator for expressjs

    Dependency Status Dev Dependency Status 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
    

    Dependencies

    How To Use

     const { validator } = require('expressjs-field-validator');
    router.get('/users/:id',
    validator([{param : 'id', location : 'params', isRequired : true}], { mode : 'reject', errorCode : '422' }),
    (req, res, next) => {
    
      // Main Service Here
    
    });

    validator arguments

    Argument Type Description
    validator Object[] Array of validation object
    Response Object This Object determines the proceeding to the next step

    validator Object

    Property Type Description
    param String Field name
    location String Location of the field (body/params/query) only mandatory for higher order objects (direclty under body/params/query) default body
    children Object[] Array of Child validator objects, only applicable if the field is Array or Object
    isArray Boolean The value is Array or not (default false)
    isObject Boolean The value is Object or not (default false)
    isRequired Boolean The value is mandatory or not (default false)
    isNumber Boolean The value is Number or not (default false)
    range Object Object {min : 1, max : 10} describes minimum and maximum value of a Number field
    isEmail Boolean The value is Email or not (default false)
    isBoolean Boolean The value is Boolean or not (default false)
    isDate Boolean The value is Date or not (default false)
    format String Date format. Please reffer https://momentjs.com/docs/ for date formats
    mobileNumber Object Object {countryCode : '91', isCountryCodeMandatory : true, length: {min : 1, max : 10}} ,describes characteristics of mobile number, length is the length range of mobile number excluding country code
    length Object Object {min : 1, max : 10} describes minimum and maximum length
    includes Object[] Value must be one of the element in the array
    excludes Object[] Value must not be one of the element in the array
    message String Error message thrown in case of test fails default : Invalid Field Error

    Nested Objets

    In case of Object or Array, isArray or isObject must be true if json structure is

    {
      "page" : {
        "sorted" : "True"
      },
      "sort" : [{
        "value" : [{
    	"date" : "2019-01-01",
    	"length" : {"min" : "1", "max" : "100"}
        }]
      }]
    }

    the validator object

    [
      {param : 'page', location : 'body', isObject : true, children : [
        {param : 'sorted', location : 'body.page', isRequired : true, isBoolean : true, message='Mandatory field page missing'},
      ]},
      {param : 'sort', location : 'body', isArray : true, children : [
        {param : 'value', location : 'body.sort', isArray : true, children : [
          {param : 'date', location : 'body.sort.value', isRequired : true, isDate : true},
          {param : 'length', location : 'body.sort.value', isObject : true, children : [
            {param : 'min', location : 'body.sort.value.length', isNumber : true},
            {param : 'max', location : 'body.sort.value.length', isNumber : true}
          ]}
        ]}
      ]}
     ]

    Response object

    Property Type Description
    mode String can be reject or forward, Mandatory field
    errorCode String Error code send in response. default 422 Error
    debug Boolean set true to respond back more details on error

    Mode

    Value can be can be reject or forward.

    Reject

    Response is sent back with http status code provided in errorCode property

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

    Error is set to request.locals.data and error code to request.locals.statusCode. Forward the request to next middleware.

    debug

    If debug is set to true, error response will be

    {
        "error": [
            {
                "location": "body.sort",
                "param": "sort",
                "message": "Invalid Field Error :: somevalueforsort Must Be A Boolean"
            }
        ]
    }

    It will give more idea about the error.

    checkService

     const { checkService } = require('expressjs-field-validator');

    It helps to skip the main service function, if you have used forward mode.

    Usage

    Pass your service function to checkService, which must be skipped.

    checkService((req, resp, next) => {
      
    })
    router.get('/users/:id',
    validator([{param : 'id', location : 'params', isRequired : true, isNumber: true}], { mode : 'forward' }),
    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

     const { skipService } = require('expressjs-field-validator');
    
     skipService(req, 'SOME-ERROR');

    Arguments

    Property Type Description
    req Object Pass the request object
    statusCode String Some status code to identify the error. Read the data from request.locals.statusCode

    It helps to skip the main service function manually.

    Usage

    Pass your service function to checkService, which must be skipped. Use skipService in the middleware which is added before the main service

    [
      (req, resp, next) => {
        skipService(req, 'SOME-ERROR');
        next();
      },
      checkService((req, resp, next) => {
        // This will be skipped
      }),
      (req, resp, next) => {
        // This will not be skipped
      }
    ]

    Install

    npm i expressjs-field-validator

    DownloadsWeekly Downloads

    60

    Version

    2.2.1

    License

    MIT

    Unpacked Size

    15.2 kB

    Total Files

    7

    Last publish

    Collaborators

    • gsmithun4