简体   繁体   中英

How to fix bug on validation 'min' Laravel 5.8

I am trying to validate an integer field using a class extension. class 扩展来验证 integer 字段。 The validation works fine in most cases but i found an issue.

The rule is

'operation_id'      => 'required|integer|min:1'

It works with values like:

operation_id: 0  //false
operation_id: 0s //false
operation_id: -1 //false
operation_id: 1  //true

But It fails when setting value

operation_id: 0\n //It throws a true when it should be a false

I am using Laravel 5.8, and I am sending the data to test requests validation through Postman.

The Laravel's integer validation is simply using PHP's filter_var function. ( Laravel Source ).

Which for some reason will parse "0\n" (zero + new line) as a valid integer 0 .

// Example:

$var = "0\n"; // This get's parsed as zero + new line
$result = filter_var($var, FILTER_VALIDATE_INT); // true

$var = '0\n'; // This is string literal "0\n"
$result = filter_var($var, FILTER_VALIDATE_INT); // FALSE

So, it seems like the integer validation passes for the above reason and the min passes because the string length (3) is > the min (1).

You can trim all the inputs before validation:

$request->merge(array_map("trim", $request->all()));

so the trim will remove all whitespace chars including newline from the string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM