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

Laravelのバリデーションの組み合わせでハマったバグと対策について

Posted at

動作環境

  • Laravel 5.5
  • php 7.2

ハマったこと

LaravelでRequestのバリデーションを以下のように記述していました。

public function messages()
{
    return [
    	.
    	.
		'max' => ':attributeは5文字以内で入力してください'
		'numeric' => ':attributeは数値で入力してください'
		.
		.
    ];
}

public function rules()
{
	return [
		.
		.
		.
		'address1' => 'required|numeric|max: 3',
		'address2' => 'required|numeric|max: 4',
		.
		.
		.
	];
}

自分が予想していた動作結果として、入力されたFormのvalueが数値かつ5文字以下のときはバリデーションエラーにならないというものでした。

しかしながら、結果として、address1に3文字の数値、address4文字の数値を入力するとaddress1は3文字以内で入力してください, address2は4文字以内で入力してくださいと出てしまいました。

対策

別のバリデーションで数字かつその文字数ならバリデーションが通るdegitsというものがあるので、こちらを使いましょう
また、数字かつその文字数の範囲になら受け付けるdegits_betweenもあります。

以下使用例

public function messages()
{
    return [
    	.
    	.
    	.
		'max' => ':attributeは5文字以内で入力してください'
		'numeric' => ':attributeは数値で入力してください'
		.
		.
		.
    ];
}

public function rules()
{
	return [
		.
		.
		'address1' => 'required|degits: 3',
		'address2' => 'required|degits_between: 1, 4',
		.
		.
	];
}
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?