Issue with Laravel Rules & Regex (OR) operator

換了新工作後才開始接觸 Laravel 這套 PHP framework,學習的過程碰到不少問題,跟之前慣用的 CodeIgniter 相比,Laravel 引了很多新觀念。

這天在使用 Laravel 內建的 Validation 作表單檢查的時候,發現 regex 規則怎麼寫都不會過….. (怒

規則如下:

<?php

$rule = array(

    'mode' => 'required|regex:/^(typeA|typeB)$/'

);

執行時會一直收到如下的錯誤訊息…

ErrorException
preg_match(): No ending delimiter '\/' found

苦惱了十分鐘後才在文件上看到這段話…

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.

因為 pipe (|) 衝突的關係… WTF…

所以要改寫成 array 的形式

<?php

$rule = array(

    'mode' => array('required', 'regex:/^(typeA|typeB)$/')

);

搞定。


Posted

in

by

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *