
Wikis & learning
Convert a validated field into an integer
An HTML form can send a number as text. Validate the value before turning it into a quantity so that an empty or inappropriate field does not silently become zero.
An HTML form can send a number as text. Validate the value before turning it into a quantity so that an empty or inappropriate field does not silently become zero.
Walkthrough
FILTER_VALIDATE_INT returns an integer on success and false for a failed check. Compare strictly with false because zero can be a valid input. The range restriction expresses a separate application decision.
PHP example
<?php
foreach (['0', '12', 'bad'] as $field) {
$qty = filter_var($field, FILTER_VALIDATE_INT, ['options' => ['min_range' => 0, 'max_range' => 50]]);
echo $field, ' = ', $qty === false ? 'invalid' : $qty, PHP_EOL;
}Expected output
0 = 0
12 = 12
bad = invalidChange and check
Try the values 0, 51, -1 and twelve. Decide whether a delivery form and an age field should apply the same range.
Discussion
Sign in to participate.



