Laravel validation rule size validation error even though the number of characters matches
Aug 29, 2020
PHP
Beginner
Laravel
For Beginners
Laravel7
Purpose
- Summarize the problem that an error occurs even if it matches with the number of characters specified in the validation rule “size” while implementing validation
Implementation environment
- Hardware environment
Item | Information |
---|---|
OS | macOS Catalina(10.15.5) |
Hardware | MacBook Pro (13-inch, 2020, Four Thunderbolt 3 ports) |
Processor | 2 GHz Quad Core Intel Core i5 |
Memory | 32 GB 3733 MHz LPDDR4 |
Graphics | Intel Iris Plus Graphics 1536 MB |
- Software environment
Item | Information | Remarks |
---|---|---|
PHP version | 7.4.3 | Introduced using Homwbrew |
Laravel version | 7.0.8 | Introduced by this method using commposer → Construct environment of Mac Laravel |
MySQL version | 8.0.19 for osx10.13 on x86_64 | Introduced by this method using Homwbrew → Install MySQL with Mac Homebrew |
Problem code
-
I wrote a process to check the postal code data sent from the view file in the process of saving the postal code.
-
Describe the processing of the action part of the controller file on the data receiving side. (The view file is processed to output a validation error.)
public function update(Request $request) { // Enter validation rules $rules = [ // Validation rule to confirm that the input postal code data is "not empty" "is a number" "character length is 7 characters" 'postal_code' => ['required','integer','size:7'], ] // validation check $this->validate($request, $rules); return redirect(route('home')); }
-
A validation error saying “The postal code must be 7.” was output to the view file.
-
It is a validation error that the number of characters is not 7.
Cause
- I made a mistake in specifying the validation rules.
- “There is another validation rule that specifies that the field is numeric and the number of digits in the value is specified.
digits: rules
can be described.
solution
-
It is necessary to modify the description part of the validation rule as follows.
-
By describing as follows, the rule that the input data is “not empty” and “the number of digits is 7” can be defined.
$rules = [ 'postal_code' => ['required','digits:7'], ]