Validating Numeric Field Length in Laravel 5
In Laravel 5, when validating a numeric input's length, it may not behave as expected. For instance, if you want to ensure that a national ID field contains exactly 10 digits, the following code:
<code class="php">$rules = [ 'national-id' => 'required|size:10|numeric' ];</code>
...will fail to validate even if the input value has 10 digits because it compares the exact equality with 10 instead of checking the length.
Solution: Using the 'digits' Rule
To properly validate the length of a numeric field, use the 'digits' rule instead of 'digits_between' or 'numeric':
<code class="php">$rules = [ 'national-id' => 'required|digits:10' ];</code>
The 'digits' rule verifies that the given value is numeric and has the specified number of digits. In this case, it will ensure that the national ID field contains exactly 10 digits.
The above is the detailed content of How to Validate the Length of a Numeric Field Correctly in Laravel 5?. For more information, please follow other related articles on the PHP Chinese website!