1
Fork 0
mirror of https://github.com/RGBCube/serenity synced 2025-05-14 10:14:58 +00:00

LibWeb: Add input element valueAsNumber

This commit is contained in:
Bastiaan van der Plaat 2023-10-04 22:40:31 +02:00 committed by Andreas Kling
parent d290569535
commit d5ca8209bf
3 changed files with 38 additions and 2 deletions

View file

@ -1137,6 +1137,39 @@ i32 HTMLInputElement::default_tab_index_value() const
return 0;
}
// https://html.spec.whatwg.org/multipage/input.html#dom-input-valueasnumber
WebIDL::ExceptionOr<double> HTMLInputElement::value_as_number() const
{
// On getting, if the valueAsNumber attribute does not apply, as defined for the input element's type attribute's current state, then return a Not-a-Number (NaN) value.
if (type_state() != TypeAttributeState::Date || type_state() != TypeAttributeState::Month || type_state() != TypeAttributeState::Week || type_state() != TypeAttributeState::Time || type_state() != TypeAttributeState::LocalDateAndTime || type_state() != TypeAttributeState::Number || type_state() != TypeAttributeState::Range)
return NAN;
// Otherwise, run the algorithm to convert a string to a number defined for that state to the element's value; if the algorithm returned a number, then return it, otherwise, return a Not-a-Number (NaN) value.
return value().to_double().value_or(NAN);
}
// https://html.spec.whatwg.org/multipage/input.html#dom-input-valueasnumber
WebIDL::ExceptionOr<void> HTMLInputElement::set_value_as_number(double value)
{
// On setting, if the new value is infinite, then throw a TypeError exception.
if (!isfinite(value))
return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "valueAsNumber: Value is infinite"sv };
// Otherwise, if the valueAsNumber attribute does not apply, as defined for the input element's type attribute's current state, then throw an "InvalidStateError" DOMException.
if (type_state() != TypeAttributeState::Date || type_state() != TypeAttributeState::Month || type_state() != TypeAttributeState::Week || type_state() != TypeAttributeState::Time || type_state() != TypeAttributeState::LocalDateAndTime || type_state() != TypeAttributeState::Number || type_state() != TypeAttributeState::Range)
return WebIDL::InvalidStateError::create(realm(), "valueAsNumber: Invalid input type used"_fly_string);
// Otherwise, if the new value is a Not-a-Number (NaN) value, then set the value of the element to the empty string.
if (value == NAN) {
m_value = "";
return {};
}
// Otherwise, run the algorithm to convert a number to a string, as defined for that state, on the new value, and set the value of the element to the resulting string.
m_value = DeprecatedString::number(value);
return {};
}
// https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#dom-cva-checkvalidity
WebIDL::ExceptionOr<bool> HTMLInputElement::check_validity()
{