Home >Backend Development >PHP Tutorial >How to Validate the Length of a Numeric Field Correctly in Laravel 5?

How to Validate the Length of a Numeric Field Correctly in Laravel 5?

DDD
DDDOriginal
2024-10-18 21:32:031085browse

How to Validate the Length of a Numeric Field Correctly in Laravel 5?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn