简体   繁体   English

Laravel正则表达式验证不起作用

[英]Laravel Regex Validation does not work

I want to define the username as 4 letters + 4 digits like " abcd1234 ". 我想将用户名定义为4个字母+ 4个数字,例如“ abcd1234 ”。 Here is my code in Laravel 5: 这是我在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! 谢谢!

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'));
[a-zA-Z]{4}\d{4}

[a-zA-Z]{4}表示4个字母\\d{4}表示4个数字

The code is correct. 代码正确。 The problem is that use App\\Http\\Requests\\Request; 问题是use App\\Http\\Requests\\Request; is missed in the RegisterRequest.php . RegisterRequest.php丢失。

The statements in the RegisterRequest.php should like this : RegisterRequest.php的语句应如下所示:

<?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 ! 最后, 'username' => 'required|regex:/^[A-Za-z]{4}\\d{4}$/|unique:users'效果很好!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM