简体   繁体   中英

Validate an array of object using express-validator

I am using express-validator to validate my request body in an API. I want to validate a request field - dataPoints which is supposed to be an array of objects. I want to check if in each of the objects, there is a key - dataType and that its value is part of an array - ["selection", "number", "text", "date"] . Here is my code

  validateParameters: () => {
    return [
      body("name").exists().withMessage("The name is required!"),
      body("description").exists().withMessage("The description is required"),
      body("dataPoints").isArray().withMessage("Datapoints can not be empty and must be an array!"),
      body("dataPoints").custom(async (value) => {
        if (value !== undefined & value.length > 0) {
          value.forEach(function (dataPoint) {
            var options = ["selection", "number", "text", "date"];
            let dataValue = dataPoint.dataType ? dataPoint.dataType : "";
            console.log(dataValue)
            if (options.indexOf(dataValue.toLowerCase()) !== -1) {
              return Promise.reject();
            }
          })
          .withMessage("Invalid data point");
        }
       
      }),
    ]
  },

I currently get this error when I run instead of Invalid data point when I pass a wrong dataType

{
    "status": "error",
    "errors": [
        {
            "message": "Cannot read property 'withMessage' of undefined"
        }
    ]
}

How do I fix this?

Also, how do I ensure that the dataPoints array contains at least one object before submitting because currently, an empty can be submitted which is wrong!

use my github link , you will get perfect answer. I have already created an small project in nodejs using express-validator for this

https://github.com/Sagar-Prajapati/ValidateRegistration/tree/master

you should use throw new Error in custom validator instead of .withMessage method here is a example:

    body("properties")
  .custom((value) => {
    if (_.isArray(value)) {
      if (value.length !== 0) {
        for (var i = 0; i < value.length; i++) {
          if (
            /^[ \u0600-\u06FF A-Za-z ][ \u0600-\u06FF A-Za-z ]+$/.test(
              value[i]
            )
          ) {
            if (i === value.length - 1) {
              return true;
            } else {
              continue;
            }
          } else {
            throw new Error("Invalid data point");
          }
        }
      } else {
        return true;
      }
    } else {
      throw new Error("Invalid data point");
    }
  })
  .optional(),

and if you wanna pass your validator you should return true

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM