26

I have a little problem in laravel validation request. I want to reject username with space like foo bar. I just want to allow foobar without space. Right now my rule is required|unique:user_detail,username. What rule should i use? thanks

6 Answers 6

68

Why don't you use alpha_dash rule?

required|alpha_dash|unique:user_detail,username

From the documentation:

The field under validation may have alpha-numeric characters, as well as dashes and underscores.

And it doesn't allow spaces.

4
  • alpha will not allow underscores for example.
    – scrubmx
    Jun 14, 2016 at 3:49
  • alpha_dash can work, it all depends on the characters you want to allow. String like: "(╯°□°)╯" will fail alpha_dash validation too.
    – scrubmx
    Jun 14, 2016 at 3:58
  • 2
    Of course it will. Do you read alpha_dash docs? The field under validation may have alpha-numeric characters, as well as dashes and underscores.
    – huuuk
    Jun 14, 2016 at 4:02
  • Try it yourself alpha_dash doesn't allow parentheses.
    – scrubmx
    Jun 14, 2016 at 4:13
27

You can extend the validator with your own custom rules:

Validator::extend('without_spaces', function($attr, $value){
    return preg_match('/^\S*$/u', $value);
});

Then just use as any other rule:

required|without_spaces|unique:user_detail,username

Checkout the docs on custom validation rules:

https://laravel.com/docs/5.2/validation#custom-validation-rules

2
  • 2
    use regex in rules instead of create new custom validation. 'username' => 'required|regex:/^\S*$/u',
    – shamaseen
    Dec 10, 2018 at 9:04
  • This simply removes spaces. Periods, commas, or other characters can still be inserted Aug 5, 2023 at 15:15
4

You should use regular expression with your validation.

PHP :

required|unique:user_detail,username,'regex:/\s/'
1
  • 4
    Thanks! But it should be regex:/^\S*$/u
    – fzlrhmn
    Jun 14, 2016 at 4:03
2

Laravel validation for username or subdomain

    "subdomain" => [
        "regex:/^[a-zA-Z0-9]+$/",
        "required", "min:3","max:20","unique:subdomains",
    ],
0
0

You should use regular expressions with your validation.

Laravel:

'domain' => 'required|max:255|unique:users|regex:/(^[a-zA-Z]+[a-zA-Z0-9\\-]*$)/u',
0

The assumption is that a username can contain either (only alphabetic letters) or a mixture of (alphabetic letters and numbers).

In that case, the rules below should work.
(for alphabetic letters) -> ['username' => 'alpha'] //eg johndoe
(for alphabetic letters and numbers) -> ['username' => 'alpha_num'] //eg johndoe123

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.