Skip to content

Commit

Permalink
Merge pull request console-rs#41 from vallentin/validate-example
Browse files Browse the repository at this point in the history
  • Loading branch information
pksunkara committed Apr 26, 2020
2 parents 33771d5 + 340b46b commit fdaba21
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
19 changes: 19 additions & 0 deletions examples/validate_input.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
extern crate dialoguer;

use dialoguer::Input;

fn main() {
let mail: String = Input::new()
.with_prompt("Enter email")
.validate_with(|input: &str| -> Result<(), &str> {
if input.contains('@') {
Ok(())
} else {
Err("This is not a mail address")
}
})
.interact()
.unwrap();

println!("Email: {}", mail);
}
17 changes: 17 additions & 0 deletions src/prompts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,23 @@ where
}

/// Registers a validator.
///
/// # Example
///
/// ```no_run
/// # use dialoguer::Input;
/// let mail: String = Input::new()
/// .with_prompt("Enter email")
/// .validate_with(|input: &str| -> Result<(), &str> {
/// if input.contains('@') {
/// Ok(())
/// } else {
/// Err("This is not a mail address")
/// }
/// })
/// .interact()
/// .unwrap();
/// ```
pub fn validate_with<V: Validator + 'static>(&mut self, validator: V) -> &mut Input<'a, T> {
let old_validator_func = self.validator.take();
self.validator = Some(Box::new(move |value: &str| -> Option<String> {
Expand Down

0 comments on commit fdaba21

Please sign in to comment.