0
0

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 3 years have passed since last update.

Laravelで半角英数字のみのバリデーション(簡単な方法)

Last updated at Posted at 2020-09-18

Laravel6系で動作した方法

前提

  • alpha
  • alpha_num
  • alpha_dash

↑ があるが、2バイト文字が考慮されていないので、全角が通ってしまう

ざっくり理解

初期のvalidatorロジックを上書きすればOK。

STEP1. App/Validators/CustomValidatorを作成する

App/Validators/CustomValidator.php


<?php

namespace App\Validators;

use Illuminate\Validation\Validator;

class CustomValidator extends Validator
{
    /**
     * alpah
     *
     * @param string $attribute
     * @param string $value
     * @return true
     */
    public function validateAlpha($attribute, $value)
    {
        return (preg_match("/^[a-z]+$/i", $value));
    }

    /**
     * alpah_dash
     *
     * @param string $attribute
     * @param string $value
     * @return true
     */
    public function validateAlphaDash($attribute, $value)
    {
        return (preg_match("/^[a-z0-9_-]+$/i", $value));
    }

    /**
     * alpah_num
     *
     * @param string $attribute
     * @param string $value
     * @return true
     */
    public function validateAlphaNum($attribute, $value)
    {
        return (preg_match("/^[a-z0-9]+$/i", $value));
    }
}

STEP.2 どこでも使えるようにする

どこでも使えるようにAppServiceProviderで、さきほど作ったValidatorを読み込む(初期のValidatorを上書き)。

app/Providers/AppServiceProvider.php

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Validator;
use App\Validators\CustomValidator;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

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

STEP3.FormRequestなどで普通に使う

他のstring,integerなどと同じように

  • alpha
  • alpha_dash
  • alpha_num

が使える。
今度は全角文字でエラーがでるようになる!

public function rules()
{
    return [
        ...
       // 全角文字でエラーがでるようになる!
       'password' => 'required|alpha_dash|min:8'
    ];
}

参考

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

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?