Laravel 5.5以降、独自のカスタム検証ルールオブジェクトを作成できます。
新しいルールを作成するには、Artisanコマンドを実行するだけです。
php artisan make:rule Id
Laravelは新しいルールクラスをapp/Rules
ディレクトリに配置します。
カスタムオブジェクト検証ルールの例は次のようになります。
<?php 名前空間App \ Rules; Illuminate \ Contracts \ Validation \ Ruleを使用します。 クラスIDはRule { private $ message;を実装します。 / *** 検証ルールに合格するかどうかを判断します。 * * @param string $ attribute * @param mixed $ value * * @return bool * / public function pass ($ attribute、$ value) { if(!$ this-> isValidCard($ value)){ $ this-> message = '身份证格式错误、请今入正确的身份证。'; falseを返します。 } trueを返します。 } / ** * @ return文字列 検証エラーメッセージを取得します。 * * / public function message() { return $ this-> message; } / ***身份证验证* @ param $ id * @return bool * / private function isValidCard($ id){ if(18!= strlen($ id)){ return false; } $ weight = [7、9、10、5、8、4、2、1、6、3、7、9、10、5、8、4、2]; $ code = ['1'、 '0'、 'X'、 '9'、 '8'、 '7'、 '6'、 '5'、 '4'、 '3'、 '2']; $ mode = 0; $ ver = substr($ id、-1); if($ ver == 'x'){ $ ver = 'X'; foreach($ weight as $ key => $ val){ if($ key == 17){ 続行; } $ digit = intval(substr($ id、$ key、1)); $ mode + = $ digit * $ val; } $ mode%= 11; if($ ver!= $ code [$ mode]){ falseを返す; } list($ month、$ day、$ year)= self :: getMDYFromCard($ id); $ check = checkdate($ month、$ day、$ year); if(!$ check){ falseを返す; } $ today = date( 'Ymd'); $ date = substr($ id、6、8); if($ date> = $ today){ falseを返す; } trueを返します。 } プライベート関数getMDYFromCard($ id){ $ date = substr($ id、6、8 ); $ year = substr($ date、0、4); $ month = substr($ date、4、2); $ day = substr($ date、6); return [$ month、$ day、$ year]; } }
コントローラに導入します。
$ rules = [ 'buyer_name' => ['regex:/ ^ [\ p {Han} | \ w] {2,30} $ / u']、 'buyer_id_number' => ['required'、new Id]、 'buyer_telephone' => '必須| unique:investor'、 ];