1

I want to define the username as 4 letters + 4 digits like "abcd1234". Here is my code in Laravel 5:

    public function rules()
    {
        return [
            'username' => 'required|regex:/^[A-Za-z]{4}\d{4}$/|unique:users',
            'email' => 'required|email|unique:users',
            'password' => 'required|confirmed|min:8'
        ];
    }

However, the regex validation does not work at all. How to solve this problem? Thanks!

1
  • 1
    can letters and digits be in any order? Commented Apr 11, 2016 at 10:14

3 Answers 3

1

The code is correct. The problem is that use App\Http\Requests\Request; is missed in the RegisterRequest.php.

The statements in the RegisterRequest.php should like this :

<?php namespace App\Http\Requests\Auth;

use App\Http\Requests\Request;

class RegisterRequest extends Request {

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'username' => 'required|regex:/^[A-Za-z]{4}\d{4}$/|unique:users',
            'email' => 'required|email|max:255|unique:users',
            'password' => 'required|min:8|confirmed',
        ];
    }

}

Finally,'username' => 'required|regex:/^[A-Za-z]{4}\d{4}$/|unique:users' works very well !

Sign up to request clarification or add additional context in comments.

Comments

0

From doc

regex:pattern

The field under validation must match the given regular expression.

Note: When using the regex pattern, it may be necessary to specify rules in an array instead of using pipe delimiters, especially if the regular expression contains a pipe character.

So, You should do something like this

$rules = array('form_field' => array('required', 'regex:foo'));

2 Comments

@rock321987 may be coincidence .
I have tried 'username' => array('required', 'regex:/^[A-Za-z]{4}\d{4}$/'). But it still does not work.
0
[a-zA-Z]{4}\d{4}

[a-zA-Z]{4} means 4 letters \d{4} means 4 digits

1 Comment

Who is asking for meaning?

Your Answer

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