type(); } /** * Checks the number and its range. * * @param Field $field Field being validated. * @param mixed $value Sanitised value. * * @return ValidationError|null The failure, or null when the value passes. */ public function validate( Field $field, mixed $value ): ?ValidationError { if ( ! is_numeric( $value ) ) { return new ValidationError( '', 'invalid_number', __( 'Please enter a number.', 'devplugins-custom-form-builder' ) ); } $number = (float) $value; $min = $field->setting( 'min', '' ); $max = $field->setting( 'max', '' ); if ( '' !== $min && is_numeric( $min ) && $number < (float) $min ) { return new ValidationError( '', 'number_too_small', sprintf( /* translators: %s: Smallest accepted number. */ __( 'Please enter a value of %s or more.', 'devplugins-custom-form-builder' ), (string) $min ), array( 'min' => (float) $min ) ); } if ( '' !== $max && is_numeric( $max ) && $number > (float) $max ) { return new ValidationError( '', 'number_too_large', sprintf( /* translators: %s: Largest accepted number. */ __( 'Please enter a value of %s or less.', 'devplugins-custom-form-builder' ), (string) $max ), array( 'max' => (float) $max ) ); } /* * The step was saved and handed to the browser, but nothing on the server * read it, so a request could send 2.5 to a field that counts in whole * units. Measured from the minimum, as the browser measures it. */ $step = $field->setting( 'step', '' ); if ( is_numeric( $step ) && (float) $step > 0 ) { $base = ( '' !== $min && is_numeric( $min ) ) ? (float) $min : 0.0; $steps = ( $number - $base ) / (float) $step; if ( abs( $steps - round( $steps ) ) > 1e-9 * max( 1.0, abs( $steps ) ) ) { return new ValidationError( '', 'number_off_step', sprintf( /* translators: %s: Step between accepted numbers. */ __( 'Please enter a value in steps of %s.', 'devplugins-custom-form-builder' ), (string) $step ), array( 'step' => (float) $step ) ); } } return null; } }