227 Followers
·
Follow

Laravel validation username no space allowed alpha_dash or regex custom rule

Image for post
Image for post

If you want to restrict the username in Laravel to only accept letters, numbers, dashes and underscores and not space inside “the username string” you have some options :

Option A:

You should simply put this regex in the validation method like:

Note: The above regex is only to avoid space. This is not to avoid other ambiguous characters in the username string.

If you mean exactly accept letters, numbers, dashes and underscores and not space you should follow the Option B.

Option B:

alpha_dash is a default Laravel validation rule which allows letters, numbers, dashes and underscores and NOT space.

When you implement alpha_dash rule, the field under validation may have alpha-numeric characters, as well as dashes and underscores.

Note -1 :

Pay attention that the usual style of validation in Laravel 5.7, 5.8 is a little different with other older versions

Note -2 :

If you use alpah_dash and enter some value with some spaces at the end or beginning, it trims and passes the validation and works perfectly.

Thank you for reading! If you enjoyed this article:

Clap it ! Share it! Follow Me in Medium!

Also I’d like to hear your opinion on this article. If you have any doubt, question or suggestion please leave a comment below.

Have a very wonderful day!

Previous Stories You will Love:

Written by

Web geek, Self-taught full-stack web developer, Learning Python, Laravel, Vuejs, UX/UI design, Nuclear Physicist PhD

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store