script/dom/form/
validation.rs1use 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
18pub(crate) trait Validatable {
20 fn as_element(&self) -> ∈
21
22 fn validity_state(&self, cx: &mut JSContext) -> DomRoot<ValidityState>;
24
25 fn is_instance_validatable(&self, no_gc: &NoGC) -> bool;
27
28 fn has_range_limitations(&self) -> bool {
30 false
31 }
32
33 fn perform_validation(
35 &self,
36 _cx: &mut JSContext,
37 _validate_flags: ValidationFlags,
38 ) -> ValidationFlags {
39 ValidationFlags::empty()
40 }
41
42 fn satisfies_constraints(&self) -> bool;
44
45 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 fn report_validity(&self, cx: &mut JSContext) -> bool {
59 if !self.is_instance_validatable(cx.no_gc()) {
61 return true;
62 }
63
64 if self.satisfies_constraints() {
65 return true;
66 }
67
68 let report = self
71 .as_element()
72 .upcast::<EventTarget>()
73 .fire_cancelable_event(cx, atom!("invalid"));
74
75 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 html_elem.Focus(cx, &FocusOptions::default());
86 }
87 }
88
89 false
91 }
92
93 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
104pub(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
111fn 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}