An Interest In:
Web News this Week
- April 25, 2024
- April 24, 2024
- April 23, 2024
- April 22, 2024
- April 21, 2024
- April 20, 2024
- April 19, 2024
August 8, 2022 06:18 pm GMT
Original Link: https://dev.to/richclarke0/using-trim-to-validate-input-strings-before-submission-to-a-db-3oim
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:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To