bigweld86's avatar

Validating a number greater than zero is failing

I gotta validate a price field which needs to be greater than zero (0.01 is valid) so I have the following validation:

$request->validate([
            'product_price' => 'required|numeric|gt:0',
        ]);

The problem is that when I enter a string in the 'product_price' field I'm getting an error:

InvalidArgumentException The values under comparison must be of the same type

why is that? I mean, I'm checking that it should be numeric before even checking that it's > 0

0 likes
3 replies
Viernes's avatar

Use input = number in Your Html input tag

lgmm's avatar

Separate the validations in two steps:

$request->validate([ 'product_price' => 'required|numeric', ]);

$request->validate([ 'product_price' => 'numeric|gt:0', ]);
Tray2's avatar

You can check this with a simple test like this

public function testExample()
{
    $product = ['product_price' => 'test'];
    $response = $this->post('/', $product);
    $response->assertSessionHasErrors(['product_price' => 'The product price must be a number.']);
 }

And the validation like this

function store(Request $request)
{
  $request->validate([
     'product_price' => 'required|numeric|gt:0'
   ]);
 } 

Gives me this result

PHPUnit 7.5.11 by Sebastian Bergmann and contributors.

.                                                                   1 / 1 (100%)

Time: 262 ms, Memory: 14.00 MB

OK (1 test, 2 assertions)

Or even better test each validation rule like this.

class ValidationTest extends TestCase
{

    public function test_the_product_price_is_required()
    {
        $product = ['product_price' => null];
        $response = $this->post('/', $product);
        $response->assertSessionHasErrors(['product_price' => 'The product price field is required.']);
    }

    public function test_the_product_price_must_be_numeric()
    {
        $product = ['product_price' => 'test'];
        $response = $this->post('/', $product);
        $response->assertSessionHasErrors(['product_price' => 'The product price must be a number.']);

    }

    public function test_the_product_price_must_be_greater_than_zero()
    {
        $product = ['product_price' => 0];
        $response = $this->post('/', $product);
        $response->assertSessionHasErrors(['product_price' => 'The product price must be greater than 0.']);
    }

Please or to participate in this conversation.