LoginSignup
4
1

laravel バリデーション regex

Last updated at Posted at 2022-06-18

概要

  • POSTされた値の範囲をバリデートするバリデーションルールrangxについてまとめる。

記載方法

  • バリデートしたい値の範囲は正規表現を用いて定義する。

  • 「ハイフン無し郵便番号を文字列で受け取りたい。しかし数字だけに限定したい。。」場合などに使えそう。

  • 下記のように記載する。

  • 「文字列OK、ただし0~9までの数字のみ」のルールを記載する。(stringバリデーションルールと組み合わせているがrangxだけでも使える)

    formRequest.php
    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'content' => ['string', 'regex:/^[0-9]+$/'],
        ];
    }
    
  • 「文字列OK、ただし特殊文字はNG」

    formRequest.php
    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'content' => ['string', 'regex:/^[0-9a-zA-Z]+$/'],
        ];
    }
    

ご注意

  • 当該バリデーションルールは内部でPHPのpreg_match関数を実行している。そのためpreg_match関数のフォーマットで値範囲を指定して上げる必要あり。
  • バリデーションルールを複数記載する場合に区切りを|で区切る方法があるがrengxを使うときは使用できない。上記の例のように配列を用いてバリデーションルールを記載すること。

参考文献

4
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
1