1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
//! Type aliases for functions used by prompts to validate user input before //! returning the values to their callers. //! //! Validators receive the user input to a given prompt and decide whether //! they are valid, returning `Ok(())` in the process, or invalid, returning //! `Err(String)`, where the `String` content is an error message to be //! displayed to the end user. //! //! When creating containers of validators, e.g. when calling `with_validators` //! in a prompt, you might need to type hint the container with one of the types //! below. //! //! This module also provides several built-in validators generated through macros, //! exported with the `builtin_validators` feature. use crate::option_answer::OptionAnswer; /// Type alias for validators that receive a string slice as the input, /// such as [Text](crate::Text) and [Password](crate::Password). /// /// If the input provided by the user is valid, your validator should return `Ok(())`. /// /// If the input is not valid, your validator should return `Err(String)`, /// where the content of `Err` is a string whose content will be displayed /// to the user as an error message. It is recommended that this value gives /// a helpful feedback to the user. /// /// # Examples /// /// ``` /// use inquire::validator::StringValidator; /// /// let validator: StringValidator = &|input| match input.chars().find(|c| c.is_numeric()) { /// Some(_) => Ok(()), /// None => Err(String::from( /// "Your password should contain at least 1 digit", /// )), /// }; /// /// assert_eq!(Ok(()), validator("hunter2")); /// assert_eq!( /// Err(String::from("Your password should contain at least 1 digit")), /// validator("password") /// ); /// ``` pub type StringValidator<'a> = &'a dyn Fn(&str) -> Result<(), String>; /// Type alias for validators used in [DateSelect](crate::DateSelect) prompts. /// /// If the input provided by the user is valid, your validator should return `Ok(())`. /// /// If the input is not valid, your validator should return `Err(String)`, /// where the content of `Err` is a string whose content will be displayed /// to the user as an error message. It is recommended that this value gives /// a helpful feedback to the user. /// /// # Examples /// /// ``` /// use chrono::{Datelike, NaiveDate, Weekday}; /// use inquire::validator::DateValidator; /// /// let validator: DateValidator = &|input| { /// if input.weekday() == Weekday::Sat || input.weekday() == Weekday::Sun { /// Err(String::from("Weekends are not allowed")) /// } else { /// Ok(()) /// } /// }; /// /// assert_eq!(Ok(()), validator(NaiveDate::from_ymd(2021, 7, 26))); /// assert_eq!( /// Err(String::from("Weekends are not allowed")), /// validator(NaiveDate::from_ymd(2021, 7, 25)) /// ); /// ``` #[cfg(feature = "date")] pub type DateValidator<'a> = &'a dyn Fn(chrono::NaiveDate) -> Result<(), String>; /// Type alias for validators used in [MultiSelect](crate::MultiSelect) prompts. /// /// If the input provided by the user is valid, your validator should return `Ok(())`. /// /// If the input is not valid, your validator should return `Err(String)`, /// where the content of `Err` is a string whose content will be displayed /// to the user as an error message. It is recommended that this value gives /// a helpful feedback to the user. /// /// # Examples /// /// ``` /// use inquire::option_answer::OptionAnswer; /// use inquire::validator::MultiOptionValidator; /// /// let validator: MultiOptionValidator = &|input| { /// if input.len() <= 2 { /// Ok(()) /// } else { /// Err(String::from("You should select at most two options")) /// } /// }; /// /// let mut ans = vec![OptionAnswer::new(0, "a"), OptionAnswer::new(1, "b")]; /// assert_eq!(Ok(()), validator(&ans)); /// /// ans.push(OptionAnswer::new(3, "d")); /// assert_eq!( /// Err(String::from("You should select at most two options")), /// validator(&ans) /// ); /// ``` pub type MultiOptionValidator<'a> = &'a dyn Fn(&[OptionAnswer]) -> Result<(), String>; /// Built-in validator that checks whether the answer is not empty. /// /// # Arguments /// /// * `$message` - optional - Error message returned by the validator. /// Defaults to "A response is required." /// /// # Examples /// /// ``` /// use inquire::{required, validator::StringValidator}; /// /// let validator: StringValidator = required!(); /// assert_eq!(Ok(()), validator("Generic input")); /// assert_eq!(Err(String::from("A response is required.")), validator("")); /// /// let validator: StringValidator = required!("No empty!"); /// assert_eq!(Ok(()), validator("Generic input")); /// assert_eq!(Err(String::from("No empty!")), validator("")); /// ``` #[macro_export] #[cfg(feature = "builtin_validators")] macro_rules! required { () => { $crate::required! {"A response is required."} }; ($message:expr) => { &|a| match a.is_empty() { true => Err(String::from($message)), false => Ok(()), } }; } /// Built-in validator that checks whether the answer length is smaller than /// or equal to the specified threshold. /// /// Be careful when using this as a StringValidator. The `len()` method used /// in this validator is not the best tool for that. See this /// [StackOverflow question](https://stackoverflow.com/questions/46290655/get-the-string-length-in-characters-in-rust) /// /// # Arguments /// /// * `$length` - Maximum length of the input. /// * `$message` - optional - Error message returned by the validator. /// Defaults to "The length of the response should be at most $length" /// /// # Examples /// /// ``` /// use inquire::{max_length, validator::StringValidator}; /// /// let validator: StringValidator = max_length!(5); /// assert_eq!(Ok(()), validator("Good")); /// assert_eq!(Err(String::from("The length of the response should be at most 5")), validator("Terrible")); /// /// let validator: StringValidator = max_length!(5, "Not too large!"); /// assert_eq!(Ok(()), validator("Good")); /// assert_eq!(Err(String::from("Not too large!")), validator("Terrible")); /// ``` #[macro_export] #[cfg(feature = "builtin_validators")] macro_rules! max_length { ($length:expr) => { $crate::max_length! {$length, format!("The length of the response should be at most {}", $length)} }; ($length:expr, $message:expr) => { { &|a| match a.len() { _len if _len <= $length => Ok(()), _ => Err(String::from($message)), } } }; } /// Built-in validator that checks whether the answer length is larger than /// or equal to the specified threshold. /// /// Be careful when using this as a StringValidator. The `len()` method used /// in this validator is not the best tool for that. See this /// [StackOverflow question](https://stackoverflow.com/questions/46290655/get-the-string-length-in-characters-in-rust) /// /// # Arguments /// /// * `$length` - Minimum length of the input. /// * `$message` - optional - Error message returned by the validator. /// Defaults to "The length of the response should be at least $length" /// /// # Examples /// /// ``` /// use inquire::{min_length, validator::StringValidator}; /// /// let validator: StringValidator = min_length!(3); /// assert_eq!(Ok(()), validator("Yes")); /// assert_eq!(Err(String::from("The length of the response should be at least 3")), validator("No")); /// /// let validator: StringValidator = min_length!(3, "You have to give me more than that!"); /// assert_eq!(Ok(()), validator("Yes")); /// assert_eq!(Err(String::from("You have to give me more than that!")), validator("No")); /// ``` #[macro_export] #[cfg(feature = "builtin_validators")] macro_rules! min_length { ($length:expr) => { $crate::min_length! {$length, format!("The length of the response should be at least {}", $length)} }; ($length:expr, $message:expr) => { { &|a| match a.len() { _len if _len >= $length => Ok(()), _ => Err(String::from($message)), } } }; } /// Built-in validator that checks whether the answer length is equal to /// the specified value. /// /// Be careful when using this as a StringValidator. The `len()` method used /// in this validator is not the best tool for that. See this /// [StackOverflow question](https://stackoverflow.com/questions/46290655/get-the-string-length-in-characters-in-rust) /// /// # Arguments /// /// * `$length` - Expected length of the input. /// * `$message` - optional - Error message returned by the validator. /// Defaults to "The length of the response should be $length" /// /// # Examples /// /// ``` /// use inquire::{length, validator::StringValidator}; /// /// let validator: StringValidator = length!(3); /// assert_eq!(Ok(()), validator("Yes")); /// assert_eq!(Err(String::from("The length of the response should be 3")), validator("No")); /// /// let validator: StringValidator = length!(3, "Three characters please."); /// assert_eq!(Ok(()), validator("Yes")); /// assert_eq!(Err(String::from("Three characters please.")), validator("No")); /// ``` #[macro_export] #[cfg(feature = "builtin_validators")] macro_rules! length { ($length:expr) => { $crate::length! {$length, format!("The length of the response should be {}", $length)} }; ($length:expr, $message:expr) => {{ &|a| match a.len() { _len if _len == $length => Ok(()), _ => Err(String::from($message)), } }}; }