1 form.inc | form_validate_number(&$element, &$form_state) |
Form element validation handler for #type 'number'.
Note that #required is validated by _form_validate() already.
Related topics
File
- core/
includes/ form.inc, line 4651 - Functions for form and batch generation and processing.
Code
function form_validate_number(&$element, &$form_state) {
$value = $element['#value'];
if ($value === '') {
return;
}
$name = empty($element['#title']) ? $element['#parents'][0] : $element['#title'];
// Ensure the input is numeric. Browser validation of <input type="number">
// should prevent this but themers could override element implementation. Same
// goes for min/max/step validation below.
if (!is_numeric($value)) {
form_error($element, t('The value for %name must be numeric.', array('%name' => $name)));
return;
}
// Ensure that the input is greater than the #min property, if set.
if (isset($element['#min']) && $value < $element['#min']) {
form_error($element, t('The value for %name must be greater than or equal to %min.', array('%name' => $name, '%min' => $element['#min'])));
}
// Ensure that the input is less than the #max property, if set.
if (isset($element['#max']) && $value > $element['#max']) {
form_error($element, t('The value for %name must be less than or equal to %max.', array('%name' => $name, '%max' => $element['#max'])));
}
if (isset($element['#step']) && strtolower($element['#step']) != 'any') {
// Check that the input is an allowed multiple of #step (offset by #min if
// #min is set).
$offset = isset($element['#min']) ? $element['#min'] : 0.0;
if (!valid_number_step($value, $element['#step'], $offset)) {
// Integer steps are the most common use case, so give a specific message.
if ($element['#step'] == 1 && is_numeric($offset) && $offset == round($offset)) {
form_error($element, t('The value for %name must be a whole number.', array('%name' => $name)));
}
else {
form_error($element, t('The value for %name must be a whole number of steps of size %step, starting from %offset.', array('%name' => $name, '%step' => $element['#step'], '%offset' => $offset)));
}
}
}
}