DEV Community

Richard
Richard

Posted on

1 1

Using .trim() to validate input strings before submission to a db✂️

I ran across this bit of code today:

 if (request.body.body.trim() === '') {
        return response.status(400).json({ body: 'Must not be empty' });
    }
Enter fullscreen mode Exit fullscreen mode

This actually made me pause. It seemed unnecessary to me. Like... why? I could easily just use something like:

 if (request.body.body === '') {...}
Enter fullscreen mode Exit fullscreen mode

To check for empty fields, right?

But the use of trim() is actually pretty smart. trim() returns a string without spaces at the start or end. Thus, for example:

let trimmy = "       foo.        "
let trimmier = "                bar              "
console.log(trimmy.trim() + trimmier.trim())
//foo.bar
Enter fullscreen mode Exit fullscreen mode

So, why use trim()? To prevent the submission of " " or or any number of empty spaces to the database. Pretty slick.
" ".trim() will return ""

Cool, huh?

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay