Best way to check if input has spaces and display error message with Express

6.2k views Asked by At

I am trying to validate a username field and I don't want any spaces in the string. I would like to display an error back to the user.

I am using express-validator express middleware to validate the inputs. It works well for every other case but I don't know the best way to validate that there are no spaces.

https://www.npmjs.com/package/express-validator

My code

This is what I have but currently a username with spaces can be stored in the database.

check('user_name').isLength({ min: 1 }).trim().withMessage('User name is required.')

Ideally something I can use with a express-validator method.

Thank you.

3

There are 3 answers

0
gustavohenke On BEST ANSWER

trim is only good for removing spaces around the string, but it doesn't work in the middle of it.

You can write a custom validator easily, though:

check('username')
  .custom(value => !/\s/.test(value))
  .withMessage('No spaces are allowed in the username')

The custom validator uses a regular expression that checks the presence of any whitespace character (could be the usual whitespace, a tab, etc), and negates the result, because the validator needs to return a truthy value to pass.

1
YouneL On

What happens is: when you use sanitizers in the validation chain, they are only applied during validation time.

If you would like to keep the sanitized value, then you should use the sanitize functions from express-validator/filter:

app.post('/some/path', [
    check('user_name').isLength({ min: 1 }).trim().withMessage('User name is required.'),
    sanitize('user_name').trim()
], function (req, res) {
    // your sanitized user_name here
    let user_name = req.body.user_name
});

If you want to always trim all the request bodies without sanitizing each field, you can use trim-request module, here is an example:

const { check, validationResult } = require('express-validator/check');
const trimRequest = require('trim-request');

app.post('/some/path', trimRequest.body, [
    check('user_name').isLength({ min: 1 }).trim().withMessage('User name is required.'),
], function (req, res) {
    // your sanitized user_name here
    let user_name = req.body.user_name
});
0
Jeremy Thille On

Another way of testing for spaces :

console.log(/ /.test("string with spaces")) // true
console.log(/ /.test("string_without_spaces")) // false

And yet another way :

console.log("string with spaces".includes(" ")) // true
console.log("string_without_spaces".includes(" ")) // false