Skip to main content

script/dom/form/
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, NoGC};
5
6use crate::dom::bindings::codegen::Bindings::HTMLElementBinding::HTMLElementMethods;
7use crate::dom::bindings::codegen::Bindings::HTMLOrSVGOrMathMLElementBinding::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};
17
18/// Trait for elements with constraint validation support
19pub(crate) trait Validatable {
20    fn as_element(&self) -> ∈
21
22    /// <https://html.spec.whatwg.org/multipage/#dom-cva-validity>
23    fn validity_state(&self, cx: &mut JSContext) -> DomRoot<ValidityState>;
24
25    /// <https://html.spec.whatwg.org/multipage/#candidate-for-constraint-validation>
26    fn is_instance_validatable(&self, no_gc: &NoGC) -> bool;
27
28    /// <https://html.spec.whatwg.org/multipage/#have-range-limitations>
29    fn has_range_limitations(&self) -> bool {
30        false
31    }
32
33    // Check if element satisfies its constraints, excluding custom errors
34    fn perform_validation(
35        &self,
36        _cx: &mut JSContext,
37        _validate_flags: ValidationFlags,
38    ) -> ValidationFlags {
39        ValidationFlags::empty()
40    }
41
42    /// <https://html.spec.whatwg.org/multipage/#concept-fv-valid>
43    fn satisfies_constraints(&self) -> bool;
44
45    /// <https://html.spec.whatwg.org/multipage/#check-validity-steps>
46    fn check_validity(&self, cx: &mut JSContext) -> bool {
47        if self.is_instance_validatable(cx.no_gc()) && !self.satisfies_constraints() {
48            self.as_element()
49                .upcast::<EventTarget>()
50                .fire_cancelable_event(cx, atom!("invalid"));
51            false
52        } else {
53            true
54        }
55    }
56
57    /// <https://html.spec.whatwg.org/multipage/#report-validity-steps>
58    fn report_validity(&self, cx: &mut JSContext) -> bool {
59        // Step 1.
60        if !self.is_instance_validatable(cx.no_gc()) {
61            return true;
62        }
63
64        if self.satisfies_constraints() {
65            return true;
66        }
67
68        // Step 1.1: Let `report` be the result of firing an event named invalid at element,
69        // with the cancelable attribute initialized to true.
70        let report = self
71            .as_element()
72            .upcast::<EventTarget>()
73            .fire_cancelable_event(cx, atom!("invalid"));
74
75        // Step 1.2. If `report` is true, for the element,
76        // report the problem, run focusing steps, scroll into view.
77        if report {
78            let flags = self.validity_state(cx).invalid_flags();
79            println!(
80                "Validation error: {}",
81                validation_message_for_flags(&self.validity_state(cx), flags)
82            );
83            if let Some(html_elem) = self.as_element().downcast::<HTMLElement>() {
84                // Run focusing steps and scroll into view.
85                html_elem.Focus(cx, &FocusOptions::default());
86            }
87        }
88
89        // Step 1.3.
90        false
91    }
92
93    /// <https://html.spec.whatwg.org/multipage/#dom-cva-validationmessage>
94    fn validation_message(&self, cx: &mut JSContext) -> DOMString {
95        if self.is_instance_validatable(cx.no_gc()) {
96            let flags = self.validity_state(cx).invalid_flags();
97            validation_message_for_flags(&self.validity_state(cx), flags)
98        } else {
99            DOMString::new()
100        }
101    }
102}
103
104/// <https://html.spec.whatwg.org/multipage/#the-datalist-element%3Abarred-from-constraint-validation>
105pub(crate) fn is_barred_by_datalist_ancestor(no_gc: &NoGC, elem: &Node) -> bool {
106    elem.upcast::<Node>()
107        .ancestors_unrooted(no_gc)
108        .any(|node| node.is::<HTMLDataListElement>())
109}
110
111// Get message for given validation flags or custom error message
112fn validation_message_for_flags(state: &ValidityState, failed_flags: ValidationFlags) -> DOMString {
113    if failed_flags.contains(ValidationFlags::CUSTOM_ERROR) {
114        state.custom_error_message().clone().root()
115    } else {
116        DOMString::from(failed_flags.to_string())
117    }
118}