solstice333
solstice333

Reputation: 3659

express-validator used in MDN express tutorial

The Express MDN tutorial here uses the following code to do a validation step

// Validate that the name field is not empty.
body('name', 'Genre name required').isLength({ min: 1 }).trim(),

What I don't get is why trim() is chained after the isLength() validation. Shouldn't it be the other way around, or is it the same semantics either way?

I did try looking around in the express-validator doc for a mention of something like this, but was unsuccessful.

UPDATE

In response to gustavohenke's answer, I think what was confusing me, was that I was seeing two sanitization points as shown in the MDN express tutorial screenshot below:

MDN express tutorial regarding validation/sanitization

so when I read the validation doc for express-validator "If you use any of the sanitizers together with validators, the validated value is the sanitized one", I was wondering which sanitization point?

From what I've characterized, however, is that the documentation in the express tutorial (that says sanitizers in the validation step only apply to that validation step and don't mutate the request, and so another sanitizer is needed) is not true anymore. In other words, I think you can do all sanitization and validation in one chain.

Upvotes: 0

Views: 131

Answers (1)

gustavohenke
gustavohenke

Reputation: 41440

To get it clear first: trim is a sanitizer, not a validator, like isLength.

Currently (as of v5.x.x), when you specify both sanitizers and validators in the same chain, sanitizers will always run before validators. If you specify more sanitizers, they will run in the order specified.

It's documented behaviour, but it's quite easy to not see it:

If you use any of the sanitizers together with validators, the validated value is the sanitized one.

This is a point of astonishment for users, as you might have guessed, and it's planned to change on an upcoming major version.

Upvotes: 1

Related Questions