leptos_forms_rs/error/
field_error.rs1use std::error::Error as StdError;
8use std::fmt;
9
10#[derive(Debug, Clone)]
12pub struct FieldError {
13 pub field: String,
14 pub message: String,
15 pub code: Option<String>,
16}
17
18impl FieldError {
19 pub fn new(field: impl Into<String>, message: impl Into<String>) -> Self {
21 Self {
22 field: field.into(),
23 message: message.into(),
24 code: None,
25 }
26 }
27
28 pub fn with_code(mut self, code: impl Into<String>) -> Self {
30 self.code = Some(code.into());
31 self
32 }
33
34 pub fn field_name(&self) -> &str {
36 &self.field
37 }
38
39 pub fn message(&self) -> &str {
41 &self.message
42 }
43
44 pub fn code(&self) -> Option<&str> {
46 self.code.as_deref()
47 }
48
49 pub fn has_code(&self) -> bool {
51 self.code.is_some()
52 }
53
54 pub fn set_code(&mut self, code: impl Into<String>) {
56 self.code = Some(code.into());
57 }
58
59 pub fn clear_code(&mut self) {
61 self.code = None;
62 }
63
64 pub fn update_message(&mut self, message: impl Into<String>) {
66 self.message = message.into();
67 }
68
69 pub fn update_field(&mut self, field: impl Into<String>) {
71 self.field = field.into();
72 }
73
74 pub fn with_field(&self, field: impl Into<String>) -> Self {
76 Self {
77 field: field.into(),
78 message: self.message.clone(),
79 code: self.code.clone(),
80 }
81 }
82
83 pub fn with_message(&self, message: impl Into<String>) -> Self {
85 Self {
86 field: self.field.clone(),
87 message: message.into(),
88 code: self.code.clone(),
89 }
90 }
91
92 pub fn with_error_code(&self, code: impl Into<String>) -> Self {
94 Self {
95 field: self.field.clone(),
96 message: self.message.clone(),
97 code: Some(code.into()),
98 }
99 }
100}
101
102impl fmt::Display for FieldError {
103 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
104 write!(f, "{}: {}", self.field, self.message)
105 }
106}
107
108impl StdError for FieldError {}
109
110impl PartialEq for FieldError {
111 fn eq(&self, other: &Self) -> bool {
112 self.field == other.field && self.message == other.message && self.code == other.code
113 }
114}
115
116impl Eq for FieldError {}