Search code examples
node.jsexpressexpress-validator

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


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.


Solution

  • 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.