12
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[Laravel]バリデーションalpha_num指定しても全角文字が通ってしまう問題

Last updated at Posted at 2016-11-16

下記記事はLarave4ですがLaravel5でも表題の事象が発生します。

追記(正規表現を使おう)

regexを使って正規表現を利用する

/**
 * Get the validation rules that apply to the request.
 *
 * @return array
 */
public function rules()
{
    return [
        'name' => 'required',
        'identifier' => 'required|regex:regex:/^[a-zA-Z0-9-]+$/|max:255',
    ];
}

alphaバリデーションについて

  • 半角英数字の入力を制限するフィールドで日本語の入力が通ってしまう悲しい

下記で対応(但し次はAttributes()が動かなくなります・・・)

App\Services\CustomValidator.phpファイルを作成

<?php
 
namespace App\Services;
 
class CustomValidator extends \Illuminate\Validation\Validator 
{
    /**
     * alpah
     *
     * @param string $attribute
     * @param string $value
     * @return true
     */
    protected function validateAlpha($attribute, $value)
    {
        return (preg_match("/^[a-z]+$/i", $value));
    }
     
    /**
     * alpah_dash
     *
     * @param string $attribute
     * @param string $value
     * @return true
     */
    protected function validateAlphaDash($attribute, $value)
    {
        return (preg_match("/^[a-z0-9_-]+$/i", $value));
    }
     
    /**
     * alpah_num
     *
     * @param string $attribute
     * @param string $value
     * @return true
     */
    protected function validateAlphaNum($attribute, $value)
    {
        return (preg_match("/^[a-z0-9]+$/i", $value));
    }
}
  • バリデーション処理を変更したい処理を記述する

App\Providers\AppServiceProvider.phpファイルでカスタムバリデーションを適用する

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
         Validator::resolver(function($translator, $data, $rules, $messages)
        {
            return new CustomValidator($translator, $data, $rules, $messages);
        });
    }

[参考サイト]
http://www.larajapan.com/category/laravel/

12
8
1

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
12
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?