express-validator issues with checkSchema

103 Views Asked by At

I'm new to express in general but I feel like my issue is unrelated. Attached below is my route with the checkSchema call to validate different fields. The intended functionality is to only validate and require the inboundTest field when the reportingALL field is set to true. I've tried a couple things and just can't seem to get it to respond

app.post("/api/submission", 
    checkSchema({
        submissionType: {
            isIn: {
                options: ["normal"],
                errorMessage: "Invalid Submission Type"
            }
        },
        reportingALL: {
            isBoolean: true
        },
        inboundTest: {
            optional: { 
                options: { 
                    nullable: true, 
                    checkFalsy: true 
                },
                if: (value, {req}) => req.body.reportingALL == false
            },
            isDecimal: {
                if: (value, {req}) => req.body.reportingALL == true
            }
        }


    }, ['body']),
    (req, res, next) => {

        let validatorErrors = validationResult(req).errors;

        if(validatorErrors.length > 0)
        {
            //Get first error
            let firstError = validationResult(req).errors[0];
            
            if(process.env.STATUS === "Development")
            {
                console.log(firstError);
                let JSONOut = {
                    status: 400,
                    message: "Bad Request",
                    path: firstError.path,
                    error: firstError.msg
                }
                res.status(400).send(JSONOut);
            }
            else
            {
                res.status(400).send(createJSONError(400,"Bad Request"));
            }

            return;
        }
        
        res.status(200).send(createJSONError(200,"Success"));
    }
);
  1. Verified that what is being sent to the route is actually a boolean value and not a string, running the same comparisons via == or === will return the proper true false values when set respectively

  2. The documentation for this wrapper on validator.js is scuffed but I like the layout, I will take suggestions on something else.

  3. I can confirm that the validation is occuring, for example, changing submissionType to something other than "normal" will throw the error invalid field as the error handle is supposed to do. So it's not like the checkSchema isn't actually working at all.

  4. I don't like the chaining it just looks gross, would prefer to it like this

Here are the docs I am using check schema.

https://express-validator.github.io/docs/api/check-schema#schema

0

There are 0 best solutions below