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