Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
August 8, 2022 06:18 pm GMT

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' });    }

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

 if (request.body.body === '') {...}

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

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?


Original Link: https://dev.to/richclarke0/using-trim-to-validate-input-strings-before-submission-to-a-db-3oim

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To