DEV Community

Richard
Richard

Posted on

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)