Skip to main content

script/dom/form/
validitystate.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/. */
4
5use std::cell::Cell;
6use std::fmt;
7
8use bitflags::bitflags;
9use dom_struct::dom_struct;
10use itertools::Itertools;
11use js::context::JSContext;
12use script_bindings::cell::{DomRefCell, Ref};
13use script_bindings::dom::UnrootedDom;
14use script_bindings::reflector::{Reflector, reflect_dom_object};
15use stylo_dom::ElementState;
16
17use crate::dom::bindings::codegen::Bindings::ElementInternalsBinding::ValidityStateFlags;
18use crate::dom::bindings::codegen::Bindings::ValidityStateBinding::ValidityStateMethods;
19use crate::dom::bindings::inheritance::Castable;
20use crate::dom::bindings::root::{Dom, DomRoot};
21use crate::dom::bindings::str::DOMString;
22use crate::dom::element::Element;
23use crate::dom::html::htmlfieldsetelement::HTMLFieldSetElement;
24use crate::dom::html::htmlformelement::FormControlElementHelpers;
25use crate::dom::node::Node;
26use crate::dom::window::Window;
27
28/// <https://html.spec.whatwg.org/multipage/#validity-states>
29#[derive(Clone, Copy, JSTraceable, MallocSizeOf)]
30pub(crate) struct ValidationFlags(u32);
31
32bitflags! {
33    impl ValidationFlags: u32 {
34        const VALUE_MISSING    = 0b0000000001;
35        const TYPE_MISMATCH    = 0b0000000010;
36        const PATTERN_MISMATCH = 0b0000000100;
37        const TOO_LONG         = 0b0000001000;
38        const TOO_SHORT        = 0b0000010000;
39        const RANGE_UNDERFLOW  = 0b0000100000;
40        const RANGE_OVERFLOW   = 0b0001000000;
41        const STEP_MISMATCH    = 0b0010000000;
42        const BAD_INPUT        = 0b0100000000;
43        const CUSTOM_ERROR     = 0b1000000000;
44    }
45}
46
47impl fmt::Display for ValidationFlags {
48    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
49        let flag_to_message = [
50            (ValidationFlags::VALUE_MISSING, "Value missing"),
51            (ValidationFlags::TYPE_MISMATCH, "Type mismatch"),
52            (ValidationFlags::PATTERN_MISMATCH, "Pattern mismatch"),
53            (ValidationFlags::TOO_LONG, "Too long"),
54            (ValidationFlags::TOO_SHORT, "Too short"),
55            (ValidationFlags::RANGE_UNDERFLOW, "Range underflow"),
56            (ValidationFlags::RANGE_OVERFLOW, "Range overflow"),
57            (ValidationFlags::STEP_MISMATCH, "Step mismatch"),
58            (ValidationFlags::BAD_INPUT, "Bad input"),
59            (ValidationFlags::CUSTOM_ERROR, "Custom error"),
60        ];
61
62        flag_to_message
63            .iter()
64            .filter_map(|&(flag, flag_str)| {
65                if self.contains(flag) {
66                    Some(flag_str)
67                } else {
68                    None
69                }
70            })
71            .format(", ")
72            .fmt(formatter)
73    }
74}
75
76/// <https://html.spec.whatwg.org/multipage/#validitystate>
77#[dom_struct]
78pub(crate) struct ValidityState {
79    reflector_: Reflector,
80    element: Dom<Element>,
81    custom_error_message: DomRefCell<DOMString>,
82    invalid_flags: Cell<ValidationFlags>,
83}
84
85impl ValidityState {
86    fn new_inherited(element: &Element) -> ValidityState {
87        ValidityState {
88            reflector_: Reflector::new(),
89            element: Dom::from_ref(element),
90            custom_error_message: DomRefCell::new(DOMString::new()),
91            invalid_flags: Cell::new(ValidationFlags::empty()),
92        }
93    }
94
95    pub(crate) fn new(
96        cx: &mut JSContext,
97        window: &Window,
98        element: &Element,
99    ) -> DomRoot<ValidityState> {
100        reflect_dom_object(cx, Box::new(ValidityState::new_inherited(element)), window)
101    }
102
103    /// <https://html.spec.whatwg.org/multipage/#custom-validity-error-message>
104    pub(crate) fn custom_error_message(&self) -> Ref<'_, DOMString> {
105        self.custom_error_message.borrow()
106    }
107
108    /// <https://html.spec.whatwg.org/multipage/#custom-validity-error-message>
109    pub(crate) fn set_custom_error_message(&self, cx: &mut JSContext, error: DOMString) {
110        *self.custom_error_message.borrow_mut() = error;
111        self.perform_validation_and_update(cx, ValidationFlags::CUSTOM_ERROR);
112    }
113
114    /// Given a set of [ValidationFlags], recalculate their value by performing
115    /// validation on this [ValidityState]'s associated element. Additionally,
116    /// if [ValidationFlags::CUSTOM_ERROR] is in `update_flags` and a custom
117    /// error has been set on this [ValidityState], the state will be updated
118    /// to reflect the existance of a custom error.
119    pub(crate) fn perform_validation_and_update(
120        &self,
121        cx: &mut JSContext,
122        update_flags: ValidationFlags,
123    ) {
124        let mut invalid_flags = self.invalid_flags.get();
125        invalid_flags.remove(update_flags);
126
127        if let Some(validatable) = self.element.as_maybe_validatable() {
128            let new_flags = validatable.perform_validation(cx, update_flags);
129            invalid_flags.insert(new_flags);
130        }
131
132        // https://html.spec.whatwg.org/multipage/#suffering-from-a-custom-error
133        if update_flags.contains(ValidationFlags::CUSTOM_ERROR) &&
134            !self.custom_error_message().is_empty()
135        {
136            invalid_flags.insert(ValidationFlags::CUSTOM_ERROR);
137        }
138
139        self.invalid_flags.set(invalid_flags);
140        self.update_pseudo_classes(cx);
141    }
142
143    pub(crate) fn update_invalid_flags(&self, update_flags: ValidationFlags) {
144        self.invalid_flags.set(update_flags);
145    }
146
147    pub(crate) fn invalid_flags(&self) -> ValidationFlags {
148        self.invalid_flags.get()
149    }
150
151    pub(crate) fn update_pseudo_classes(&self, cx: &mut JSContext) {
152        if self.element.is_instance_validatable(cx.no_gc()) {
153            let is_valid = self.invalid_flags.get().is_empty();
154            self.element.set_state(ElementState::VALID, is_valid);
155            self.element.set_state(ElementState::INVALID, !is_valid);
156        } else {
157            self.element.set_state(ElementState::VALID, false);
158            self.element.set_state(ElementState::INVALID, false);
159        }
160
161        if let Some(form_control) = self.element.as_maybe_form_control() &&
162            let Some(form_owner) = form_control.form_owner()
163        {
164            form_owner.update_validity(cx);
165        }
166
167        if let Some(fieldset) = self
168            .element
169            .upcast::<Node>()
170            .ancestors_unrooted(cx.no_gc())
171            .find_map(UnrootedDom::downcast::<HTMLFieldSetElement>)
172            .map(|node| node.as_rooted())
173        {
174            fieldset.update_validity(cx);
175        }
176    }
177}
178
179impl ValidityStateMethods<crate::DomTypeHolder> for ValidityState {
180    /// <https://html.spec.whatwg.org/multipage/#dom-validitystate-valuemissing>
181    fn ValueMissing(&self) -> bool {
182        self.invalid_flags()
183            .contains(ValidationFlags::VALUE_MISSING)
184    }
185
186    /// <https://html.spec.whatwg.org/multipage/#dom-validitystate-typemismatch>
187    fn TypeMismatch(&self) -> bool {
188        self.invalid_flags()
189            .contains(ValidationFlags::TYPE_MISMATCH)
190    }
191
192    /// <https://html.spec.whatwg.org/multipage/#dom-validitystate-patternmismatch>
193    fn PatternMismatch(&self) -> bool {
194        self.invalid_flags()
195            .contains(ValidationFlags::PATTERN_MISMATCH)
196    }
197
198    /// <https://html.spec.whatwg.org/multipage/#dom-validitystate-toolong>
199    fn TooLong(&self) -> bool {
200        self.invalid_flags().contains(ValidationFlags::TOO_LONG)
201    }
202
203    /// <https://html.spec.whatwg.org/multipage/#dom-validitystate-tooshort>
204    fn TooShort(&self) -> bool {
205        self.invalid_flags().contains(ValidationFlags::TOO_SHORT)
206    }
207
208    /// <https://html.spec.whatwg.org/multipage/#dom-validitystate-rangeunderflow>
209    fn RangeUnderflow(&self) -> bool {
210        self.invalid_flags()
211            .contains(ValidationFlags::RANGE_UNDERFLOW)
212    }
213
214    /// <https://html.spec.whatwg.org/multipage/#dom-validitystate-rangeoverflow>
215    fn RangeOverflow(&self) -> bool {
216        self.invalid_flags()
217            .contains(ValidationFlags::RANGE_OVERFLOW)
218    }
219
220    /// <https://html.spec.whatwg.org/multipage/#dom-validitystate-stepmismatch>
221    fn StepMismatch(&self) -> bool {
222        self.invalid_flags()
223            .contains(ValidationFlags::STEP_MISMATCH)
224    }
225
226    /// <https://html.spec.whatwg.org/multipage/#dom-validitystate-badinput>
227    fn BadInput(&self) -> bool {
228        self.invalid_flags().contains(ValidationFlags::BAD_INPUT)
229    }
230
231    /// <https://html.spec.whatwg.org/multipage/#dom-validitystate-customerror>
232    fn CustomError(&self) -> bool {
233        self.invalid_flags().contains(ValidationFlags::CUSTOM_ERROR)
234    }
235
236    /// <https://html.spec.whatwg.org/multipage/#dom-validitystate-valid>
237    fn Valid(&self) -> bool {
238        self.invalid_flags().is_empty()
239    }
240}
241
242impl From<&ValidityStateFlags> for ValidationFlags {
243    fn from(flags: &ValidityStateFlags) -> Self {
244        let mut bits = ValidationFlags::empty();
245        if flags.valueMissing {
246            bits |= ValidationFlags::VALUE_MISSING;
247        }
248        if flags.typeMismatch {
249            bits |= ValidationFlags::TYPE_MISMATCH;
250        }
251        if flags.patternMismatch {
252            bits |= ValidationFlags::PATTERN_MISMATCH;
253        }
254        if flags.tooLong {
255            bits |= ValidationFlags::TOO_LONG;
256        }
257        if flags.tooShort {
258            bits |= ValidationFlags::TOO_SHORT;
259        }
260        if flags.rangeUnderflow {
261            bits |= ValidationFlags::RANGE_UNDERFLOW;
262        }
263        if flags.rangeOverflow {
264            bits |= ValidationFlags::RANGE_OVERFLOW;
265        }
266        if flags.stepMismatch {
267            bits |= ValidationFlags::STEP_MISMATCH;
268        }
269        if flags.badInput {
270            bits |= ValidationFlags::BAD_INPUT;
271        }
272        if flags.customError {
273            bits |= ValidationFlags::CUSTOM_ERROR;
274        }
275        bits
276    }
277}