user6186801
user6186801

Reputation:

Laravel Regex Validation does not work

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!

Upvotes: 1

Views: 6647

Answers (3)

Prabhat-VS
Prabhat-VS

Reputation: 1530

[a-zA-Z]{4}\d{4}

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

Upvotes: 0

user6186801
user6186801

Reputation:

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 !

Upvotes: 1

Drudge Rajen
Drudge Rajen

Reputation: 7987

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'));

Upvotes: 0

Related Questions