console-rs / dialoguer

Rust utility library for nice command line prompts and similar things
MIT License
1.31k stars 143 forks source link

Record input to history before validation #273

Closed Gordon01 closed 1 year ago

Gordon01 commented 1 year ago

One of the main reasons to use history is the ability to correct mistakes. When used with validation, history is appended after validation, so the input not passing it doesn't end up in history. Therefore, the user needs to re-type the whole text.

With this PR, history is written before input validation, so we have a complete history. This behavior is in line with tools like bash.

Input::with_theme(&theme)
    .with_prompt("E-mail")
    .history_with(&mut history)
    .validate_with(|email: &String| -> Result<(), String> {
        if !email.contains('@') {
            return Err(format!("{}: '{}'", "Invalid email address", email));
        }
    })
    .interact_text()
    .expect("Unable to read email")