← All writing

Validate a form integer before casting it

PHP 8.3+Sources checked 2026-09-13

Casting a string to an integer is a conversion, not a validation rule. A malformed quantity can become a plausible number, and a legitimate zero can be lost if the validation result is tested loosely.

Reject false, accept zero

<?php
$options = ['options' => ['min_range' => 0, 'max_range' => 500]];
$zero = filter_var('0', FILTER_VALIDATE_INT, $options);
$bad = filter_var('12 boxes', FILTER_VALIDATE_INT, $options);
assert($zero === 0);
assert($bad === false);
assert(filter_var('501', FILTER_VALIDATE_INT, $options) === false);

A strict false comparison separates invalid input from a valid zero. Choose a business maximum rather than accepting every integer the machine can represent. If the field represents an external code with leading zeroes, it probably should not be an integer at all.

Write down the accepted representation

Should a plus sign be accepted? What about leading spaces, decimal notation, or leading zeroes? Different validation mechanisms accept different representations. A quantity contract should answer those questions before a cast or database write occurs.

Laravel request validation is normally the right integration point in a Laravel app. This standalone example explains the underlying distinction and is useful in import scripts or small PHP services. Do not combine several permissive conversions until some value finally passes.

Test zero, the minimum, the maximum, one above it, negative values, arrays, and mixed text. Keep an invalid input error close to the field so the user can correct it; a generic database exception is a poor substitute for a clear quantity rule.

Reference

Official documentation. The examples here illustrate the stated boundary; adapt them to your application and test its failure paths.