wiki.techinc.nl/includes/htmlform/fields/HTMLFloatField.php
Siddharth VP 4fb27b070e htmlform: fix min/max validations on empty input in int/float fields
Int and float fields that are optional cannot currently specify the min
attribute. An unfilled value fails the validation because in PHP 8 any
number is greater than the empty string.

(For comparing numbers with non-numeric strings, the number is first
converted to a string and then compared. In PHP 7, the string was
converted to a number instead.)

Bug: T397883
Bug: T397643
Change-Id: I37be84554708e17eee27a7e599815891787e95bf
(cherry picked from commit 8e7ae749c0870e8133d083ac4125280c11a12ea6)
2025-06-28 12:49:28 +00:00

64 lines
1.4 KiB
PHP

<?php
namespace MediaWiki\HTMLForm\Field;
/**
* A field that will contain a numeric value
*
* @stable to extend
*/
class HTMLFloatField extends HTMLTextField {
public function getSize() {
return $this->mParams['size'] ?? 20;
}
public function validate( $value, $alldata ) {
$p = parent::validate( $value, $alldata );
if ( $p !== true ) {
return $p;
}
$value = trim( $value ?? '' );
if ( $value === '' ) {
return true;
}
# https://www.w3.org/TR/html5/infrastructure.html#floating-point-numbers
# with the addition that a leading '+' sign is ok.
if ( !preg_match( '/^((\+|\-)?\d+(\.\d+)?(E(\+|\-)?\d+)?)?$/i', $value ) ) {
return $this->msg( 'htmlform-float-invalid' );
}
# The "int" part of these message names is rather confusing.
# They make equal sense for all numbers.
if ( isset( $this->mParams['min'] ) ) {
$min = $this->mParams['min'];
if ( $min > $value ) {
return $this->msg( 'htmlform-int-toolow', $min );
}
}
if ( isset( $this->mParams['max'] ) ) {
$max = $this->mParams['max'];
if ( $max < $value ) {
return $this->msg( 'htmlform-int-toohigh', $max );
}
}
return true;
}
/**
* @inheritDoc
* @stable to override
*/
protected function getInputWidget( $params ) {
return new \OOUI\NumberInputWidget( $params );
}
}
/** @deprecated class alias since 1.42 */
class_alias( HTMLFloatField::class, 'HTMLFloatField' );