Giter Site home page Giter Site logo

wgrisa / express-yup-middleware Goto Github PK

View Code? Open in Web Editor NEW
15.0 2.0 2.0 374 KB

express-yup-middleware is an express middleware that uses Yup schemas to validate a request and return a response with errors.

License: MIT License

TypeScript 100.00%
hacktoberfest yup express middleware validation rest restful

express-yup-middleware's Introduction

express-yup-middleware

npm version

express-yup-middleware is an express middleware that uses Yup schemas to validate a request and return a response with errors.

Basic schema validation

import { expressYupMiddleware } from 'express-yup-middleware'

import * as Yup from 'yup'

const schemaValidator = {
  schema: {
    query: {
      yupSchema: Yup.object().shape({
        testQueryParam: Yup.string().required('requiredTestQueryParam'),
      }),
    },
    body: {
      yupSchema: Yup.object().shape({
        testBodyProperty: Yup.string().required('requiredTestBodyProperty'),
      }),
    },
    params: {
      yupSchema: Yup.object().shape({
        testParams: Yup.string().required('requiredTestParams'),
      }),
    },
  },
}

app.post('/test', expressYupMiddleware({ schemaValidator }))
{
  "errors": {
    "params": [
      {
        "message": "requiredTestParams",
        "propertyPath": "testParams"
      }
    ],
    "body": [
      {
        "message": "requiredTestBodyProperty",
        "propertyPath": "testBodyProperty"
      }
    ],
    "query": [
      {
        "message": "requiredTestQueryParam",
        "propertyPath": "testQueryParam"
      }
    ]
  }
}

Using YUP validation options

You can provide options to the property you are validating by using the validateOptions property.

YUP default configuration aborts early after a validation error. As you can see in the following example, you can change this configuration by sending abortEarly: false to the validateOptions property. There are other options available.

const schemaValidator: ExpressYupMiddlewareInterface = {
      schema: {
        body: {
          yupSchema: Yup.object().shape({
            firstTestBodyProperty: Yup.string().required('requiredFirstTestBodyProperty'),
            secondTestBodyProperty: Yup.string().required('requiredSecondTestBodyProperty'),
          }),
          validateOptions: {
            abortEarly: false,
          },
        },
      },
    }
{
  "errors": {
    "body": [
      {
        "message": "requiredFirstTestBodyProperty",
        "propertyPath": "firstTestBodyProperty"
      },
      {
        "message": "requiredSecondTestBodyProperty",
        "propertyPath": "secondTestBodyProperty"
      }
    ]
  }
}

Setting custom error messages

Make sure the key in the Yup schema (requiredTestBodyProperty) matches the property name in the error messages object.

const schemaValidator = {
  schema: {
    body: {
      yupSchema: Yup.object().shape({
        testBodyProperty: Yup.string().required('requiredTestBodyProperty'),
      }),
    },
  },
  errorMessages: {
    requiredTestBodyProperty: {
      key: 'tes-body-property-required',
      message: 'The "testBodyProperty" property is required!',
    },
  },
}
{
  "errors": {
    "body": [
      {
        "key": "tes-body-property-required",
        "message": "The \"testBodyProperty\" property is required!",
        "propertyPath": "testBodyProperty"
      }
    ]
  }
}

Cross-validation using any properties from your payload

You can cross-validate properties of your payload using a custom Yup test and accessing them by calling this.options.context.

const schemaValidator = {
  schema: {
    body: {
      yupSchema: Yup.object().shape({
        numberToValidate: Yup.string().test({
          message: 'Check if your number corresponds with the given type',
          test(this: Yup.TestContext, numberToValidate: any) {
            const mod = numberToValidate % 2
            // As you can see in the next line, the req is passed to the context
            const type = this.options.context['payload'].params.type

            if (!type) {
              return false
            }

            if (type === 'even') {
              return mod === 0
            }

            if (type === 'odd') {
              return mod !== 0
            }

            return false
          },
        }),
      }),
    },
  },
}

app.post('/test/:type', expressYupMiddleware({ schemaValidator }))

Validating a custom property in the request

The middleware default properties checked in the req (Express request) are body, params and query. If you want to validate anything else, you need to use the following option.

const schemaValidator = {
  schema: {
    headers: {
      yupSchema: Yup.object().shape({
        testHeaderProperty: Yup.string().required('requiredHeaderProperty'),
      }),
    },
  },
}

app.post('/test', expressYupMiddleware({ schemaValidator, propertiesToValidate: ['headers'] }))
{
  "errors": {
    "headers": [
      {
        "message": "requiredHeaderProperty",
        "propertyPath": "testHeaderProperty"
      }
    ]
  }
}

Using a custom error status code

Adding the expectedStatusCode option, your will receive the given status code if anything fails during the validation.

app.post('/test', expressYupMiddleware({ schemaValidator, expectedStatusCode: 418 }))

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.