script/dom/
validation.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4use js::context::JSContext;
5
6use crate::dom::bindings::codegen::Bindings::HTMLElementBinding::HTMLElementMethods;
7use crate::dom::bindings::codegen::Bindings::HTMLOrSVGElementBinding::FocusOptions;
8use crate::dom::bindings::inheritance::Castable;
9use crate::dom::bindings::root::DomRoot;
10use crate::dom::bindings::str::DOMString;
11use crate::dom::element::Element;
12use crate::dom::eventtarget::EventTarget;
13use crate::dom::html::htmldatalistelement::HTMLDataListElement;
14use crate::dom::html::htmlelement::HTMLElement;
15use crate::dom::node::Node;
16use crate::dom::validitystate::{ValidationFlags, ValidityState};
17use crate::script_runtime::CanGc;
18
19/// Trait for elements with constraint validation support
20pub(crate) trait Validatable {
21    fn as_element(&self) -> ∈
22
23    /// <https://html.spec.whatwg.org/multipage/#dom-cva-validity>
24    fn validity_state(&self, can_gc: CanGc) -> DomRoot<ValidityState>;
25
26    /// <https://html.spec.whatwg.org/multipage/#candidate-for-constraint-validation>
27    fn is_instance_validatable(&self) -> bool;
28
29    // Check if element satisfies its constraints, excluding custom errors
30    fn perform_validation(
31        &self,
32        _validate_flags: ValidationFlags,
33        _can_gc: CanGc,
34    ) -> ValidationFlags {
35        ValidationFlags::empty()
36    }
37
38    /// <https://html.spec.whatwg.org/multipage/#concept-fv-valid>
39    fn satisfies_constraints(&self, can_gc: CanGc) -> bool {
40        self.validity_state(can_gc).invalid_flags().is_empty()
41    }
42
43    /// <https://html.spec.whatwg.org/multipage/#check-validity-steps>
44    fn check_validity(&self, cx: &mut JSContext) -> bool {
45        if self.is_instance_validatable() && !self.satisfies_constraints(CanGc::from_cx(cx)) {
46            self.as_element()
47                .upcast::<EventTarget>()
48                .fire_cancelable_event(atom!("invalid"), CanGc::from_cx(cx));
49            false
50        } else {
51            true
52        }
53    }
54
55    /// <https://html.spec.whatwg.org/multipage/#report-validity-steps>
56    fn report_validity(&self, cx: &mut JSContext) -> bool {
57        // Step 1.
58        if !self.is_instance_validatable() {
59            return true;
60        }
61
62        if self.satisfies_constraints(CanGc::from_cx(cx)) {
63            return true;
64        }
65
66        // Step 1.1: Let `report` be the result of firing an event named invalid at element,
67        // with the cancelable attribute initialized to true.
68        let report = self
69            .as_element()
70            .upcast::<EventTarget>()
71            .fire_cancelable_event(atom!("invalid"), CanGc::from_cx(cx));
72
73        // Step 1.2. If `report` is true, for the element,
74        // report the problem, run focusing steps, scroll into view.
75        if report {
76            let flags = self.validity_state(CanGc::from_cx(cx)).invalid_flags();
77            println!(
78                "Validation error: {}",
79                validation_message_for_flags(&self.validity_state(CanGc::from_cx(cx)), flags)
80            );
81            if let Some(html_elem) = self.as_element().downcast::<HTMLElement>() {
82                // Run focusing steps and scroll into view.
83                html_elem.Focus(&FocusOptions::default(), CanGc::from_cx(cx));
84            }
85        }
86
87        // Step 1.3.
88        false
89    }
90
91    /// <https://html.spec.whatwg.org/multipage/#dom-cva-validationmessage>
92    fn validation_message(&self) -> DOMString {
93        if self.is_instance_validatable() {
94            let flags = self.validity_state(CanGc::note()).invalid_flags();
95            validation_message_for_flags(&self.validity_state(CanGc::note()), flags)
96        } else {
97            DOMString::new()
98        }
99    }
100}
101
102/// <https://html.spec.whatwg.org/multipage/#the-datalist-element%3Abarred-from-constraint-validation>
103pub(crate) fn is_barred_by_datalist_ancestor(elem: &Node) -> bool {
104    elem.upcast::<Node>()
105        .ancestors()
106        .any(|node| node.is::<HTMLDataListElement>())
107}
108
109// Get message for given validation flags or custom error message
110fn validation_message_for_flags(state: &ValidityState, failed_flags: ValidationFlags) -> DOMString {
111    if failed_flags.contains(ValidationFlags::CUSTOM_ERROR) {
112        state.custom_error_message().clone()
113    } else {
114        DOMString::from(failed_flags.to_string())
115    }
116}