Anshul
Anshul

Reputation: 11

How to use request body value in the .withMessage() function in express validator chain

I want to display my express validator errors with the dynamic value user entered.

For example, a user enters an invalid username (lets say "$@#") pattern (I will attach my regex somewhere) I want to send my error message as a response like this :

{
    "errorCode" : "234",
    "field" : "username",
    "value " : "$@#",
    "msg" : "Username : [$@#] is an invalid username pattern, please check the rules for valid usernames"
}

I want to achieve this with .withMessage() in the validation chain.

My current chain code :

check('username')
    .trim()
    .not()
    .isEmpty()
    .withMessage('username can\'t be empty')
    .bail()
    .matches("^[a-zA-Z0-9]([._-](?![._-])|[a-zA-Z0-9]){3,18}[a-zA-Z0-9]$")
    .withMessage(
        {
            errorCode: '234',
            field : 'username',
            value : ? ,
            msg: 'Username : [?] is an invalid username pattern, please check the rules for valid usernames'

        })

Since I can't access my req.body inside how can I achieve it?

Thanks

Upvotes: 1

Views: 552

Answers (1)

NineDeuceCad
NineDeuceCad

Reputation: 1

You can use a function to get the value from a parameter:

.withMessage((value) => { return `Invalid value: ${value}` })

Adapting that to your solution looks like this:

.withMessage(
    (value) => {
        return {
            "errorCode": 234,
            "field": 'username',
            "value": value,
            "msg": `Username: ${value} is an invalid username pattern, please check the rules for valid usernames`
        }
    })

And, if you want, you can sanitize the input value first with something like:

.escape().withMessage(...)

Upvotes: 0

Related Questions