Struct inquire::CustomType

source ·
pub struct CustomType<'a, T> {
    pub message: &'a str,
    pub default: Option<T>,
    pub placeholder: Option<&'a str>,
    pub help_message: Option<&'a str>,
    pub formatter: CustomTypeFormatter<'a, T>,
    pub default_value_formatter: CustomTypeFormatter<'a, T>,
    pub parser: CustomTypeParser<'a, T>,
    pub validators: Vec<Box<dyn CustomTypeValidator<T>>>,
    pub error_message: String,
    pub render_config: RenderConfig<'a>,
}
Expand description

Generic prompt suitable for when you need to parse the user input into a specific type, for example an f64 or a rust_decimal, maybe even an uuid.

This prompt has all of the validation, parsing and error handling features built-in to reduce as much boilerplaste as possible from your prompts. Its defaults are necessarily very simple in order to cover a large range of generic cases, for example a “Invalid input” error message.

You can customize as many aspects of this prompt as you like: prompt message, help message, default value, placeholder, value parser and value formatter.

Behavior

When initializing this prompt via the new() method, some constraints on the return type T are added to make sure we can apply a default parser and formatter to the prompt.

The default parser calls the str.parse method, which means that T must implement the FromStr trait. When the parsing fails for any reason, a default error message “Invalid input” is displayed to the user.

After the user submits, the prompt handler tries to parse the input into the expected type. If the operation succeeds, the value is returned to the prompt caller. If it fails, the message defined in error_message is displayed to the user.

The default formatter simply calls to_string() on the parsed value, which means that T must implement the ToString trait, which normally happens implicitly when you implement the Display trait.

If your type T does not satisfy these constraints, you can always manually instantiate the entire struct yourself like this:

use inquire::{CustomType, ui::RenderConfig};

let amount_prompt: CustomType<f64> = CustomType {
    message: "How much is your travel going to cost?",
    formatter: &|i| format!("${:.2}", i),
    default_value_formatter: &|i| format!("${:.2}", i),
    default: None,
    validators: vec![],
    placeholder: Some("123.45"),
    error_message: "Please type a valid number.".into(),
    help_message: "Do not use currency and the number should use dots as the decimal separator.".into(),
    parser: &|i| match i.parse::<f64>() {
        Ok(val) => Ok(val),
        Err(_) => Err(()),
    },
    render_config: RenderConfig::default(),
};

Example

use inquire::CustomType;

let amount = CustomType::<f64>::new("How much do you want to donate?")
    .with_formatter(&|i| format!("${:.2}", i))
    .with_error_message("Please type a valid number")
    .with_help_message("Type the amount in US dollars using a decimal point as a separator")
    .prompt();

match amount {
    Ok(_) => println!("Thanks a lot for donating that much money!"),
    Err(_) => println!("We could not process your donation"),
}

Fields§

§message: &'a str

Message to be presented to the user.

§default: Option<T>

Default value, returned when the user input is empty.

§placeholder: Option<&'a str>

Short hint that describes the expected value of the input.

§help_message: Option<&'a str>

Help message to be presented to the user.

§formatter: CustomTypeFormatter<'a, T>

Function that formats the user input and presents it to the user as the final rendering of the prompt.

§default_value_formatter: CustomTypeFormatter<'a, T>

Function that formats the provided value. Useful for example when you want to format a default true to the string “Y/n”, common in confirmation prompts.

§parser: CustomTypeParser<'a, T>

Function that parses the user input and returns the result value.

§validators: Vec<Box<dyn CustomTypeValidator<T>>>

Collection of validators to apply to the user input.

Validators are executed in the order they are stored, stopping at and displaying to the user only the first validation error that might appear.

The possible error is displayed to the user one line above the prompt.

§error_message: String

Error message displayed when value could not be parsed from input.

§render_config: RenderConfig<'a>

RenderConfig to apply to the rendered interface.

Note: The default render config considers if the NO_COLOR environment variable is set to decide whether to render the colored config or the empty one.

When overriding the config in a prompt, NO_COLOR is no longer considered and your config is treated as the only source of truth. If you want to customize colors and still suport NO_COLOR, you will have to do this on your end.

Implementations§

source§

impl<'a, T> CustomType<'a, T>where T: Clone,

source

pub const DEFAULT_VALIDATORS: Vec<Box<dyn CustomTypeValidator<T>>> = _

Default validators added to the CustomType prompt, none.

source

pub fn new(message: &'a str) -> Selfwhere T: FromStr + ToString,

Creates a CustomType with the provided message and default configuration values.

Examples found in repository?
examples/manual_date_input.rs (line 5)
4
5
6
7
8
9
10
11
12
13
14
15
16
17
fn main() {
    let amount = CustomType::<NaiveDate>::new("When are you going to visit the office?")
        .with_placeholder("dd/mm/yyyy")
        .with_parser(&|i| NaiveDate::parse_from_str(i, "%d/%m/%Y").map_err(|_| ()))
        .with_formatter(DEFAULT_DATE_FORMATTER)
        .with_error_message("Please type a valid date.")
        .with_help_message("The necessary arrangements will be made")
        .prompt();

    match amount {
        Ok(_) => println!("Thanks! We will be expecting you."),
        Err(_) => println!("We could not process your reservation"),
    }
}
More examples
Hide additional examples
examples/date.rs (line 25)
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
fn custom_type_parsed_date_prompt() {
    println!("-------> Date parsed from text input with Custom Type prompt");
    println!();

    let amount = CustomType::<NaiveDate>::new("When are you going to visit the office?")
        .with_placeholder("dd/mm/yyyy")
        .with_parser(&|i| NaiveDate::parse_from_str(i, "%d/%m/%Y").map_err(|_| ()))
        .with_formatter(DEFAULT_DATE_FORMATTER)
        .with_error_message("Please type a valid date.")
        .with_help_message("The necessary arrangements will be made")
        .prompt();

    match amount {
        Ok(_) => println!("Thanks! We will be expecting you."),
        Err(_) => println!("We could not process your reservation"),
    }
    println!();
}
examples/custom_type.rs (line 4)
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
fn main() {
    let amount = CustomType::<f64>::new("How much do you want to donate?")
        .with_formatter(&|i| format!("${i:.2}"))
        .with_error_message("Please type a valid number")
        .with_help_message("Type the amount in US dollars using a decimal point as a separator")
        .with_validator(|val: &f64| {
            if *val <= 0.0f64 {
                Ok(Validation::Invalid(
                    "You must donate a positive amount of dollars".into(),
                ))
            } else {
                Ok(Validation::Valid)
            }
        })
        .prompt();

    match amount {
        Ok(_) => println!("Thanks a lot for donating that much money!"),
        Err(_) => println!("We could not process your donation"),
    }
}
examples/expense_tracker.rs (line 20)
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
fn main() -> InquireResult<()> {
    let _date = DateSelect::new("Date:").prompt()?;

    let _category = Select::new("Category:", get_categories()).prompt()?;

    let _payee = Text::new("Payee:")
        .with_validator(required!("This field is required"))
        .with_autocomplete(&payee_suggestor)
        .with_help_message("e.g. Music Store")
        .with_page_size(5)
        .prompt()?;

    let amount: f64 = CustomType::new("Amount:")
        .with_formatter(&|i: f64| format!("${i}"))
        .with_error_message("Please type a valid number")
        .with_help_message("Type the amount in US dollars using a decimal point as a separator")
        .prompt()
        .unwrap();

    let _description = Text::new("Description:")
        .with_help_message("Optional notes")
        .prompt()?;

    let mut accounts = get_accounts();
    let accounts_mut = accounts.iter_mut().collect();
    let account = Select::new("Account:", accounts_mut).prompt()?;
    account.balance -= amount;

    let _tags = MultiSelect::new("Tags:", get_tags()).prompt()?;

    println!("Your transaction has been successfully recorded.");
    println!("The balance of {} is now ${:.2}", account, account.balance);

    Ok(())
}
examples/empty_render_config.rs (line 24)
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
fn main() -> InquireResult<()> {
    inquire::set_global_render_config(RenderConfig::empty());

    let _date = DateSelect::new("Date:").prompt()?;

    let _category = Select::new("Category:", get_categories()).prompt()?;

    let _payee = Text::new("Payee:")
        .with_validator(required!("This field is required"))
        .with_autocomplete(&payee_suggestor)
        .with_help_message("e.g. Music Store")
        .with_page_size(5)
        .prompt()?;

    let amount: f64 = CustomType::new("Amount:")
        .with_formatter(&|i: f64| format!("${i}"))
        .with_error_message("Please type a valid number")
        .with_help_message("Type the amount in US dollars using a decimal point as a separator")
        .prompt()
        .unwrap();

    let _description = Text::new("Description:")
        .with_help_message("Optional notes")
        .prompt()?;

    let mut accounts = get_accounts();
    let accounts_mut = accounts.iter_mut().collect();
    let account = Select::new("Account:", accounts_mut).prompt()?;
    account.balance -= amount;

    let _tags = MultiSelect::new("Tags:", get_tags()).prompt()?;

    println!("Your transaction has been successfully recorded.");
    println!("The balance of {account} is now $311.09");

    Ok(())
}
examples/render_config.rs (line 24)
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
fn main() -> InquireResult<()> {
    inquire::set_global_render_config(get_render_config());

    let _date = DateSelect::new("Date:").prompt()?;

    let _category = Select::new("Category:", get_categories()).prompt()?;

    let _payee = Text::new("Payee:")
        .with_validator(required!("This field is required"))
        .with_autocomplete(&payee_suggestor)
        .with_help_message("e.g. Music Store")
        .with_page_size(5)
        .prompt()?;

    let amount: f64 = CustomType::new("Amount:")
        .with_formatter(&|i: f64| format!("${i}"))
        .with_error_message("Please type a valid number")
        .with_help_message("Type the amount in US dollars using a decimal point as a separator")
        .prompt()
        .unwrap();

    let _description = Text::new("Description:")
        .with_help_message("Optional notes")
        .prompt()?;

    let mut accounts = get_accounts();
    let accounts_mut = accounts.iter_mut().collect();
    let account = Select::new("Account:", accounts_mut).prompt()?;
    account.balance -= amount;

    let _tags = MultiSelect::new("Tags:", get_tags()).prompt()?;

    println!("Your transaction has been successfully recorded.");
    println!(
        "The balance of {} is now ${:.2}",
        account.name, account.balance
    );

    Ok(())
}
source

pub fn with_default(self, default: T) -> Self

Sets the default input.

source

pub fn with_placeholder(self, placeholder: &'a str) -> Self

Sets the placeholder.

Examples found in repository?
examples/manual_date_input.rs (line 6)
4
5
6
7
8
9
10
11
12
13
14
15
16
17
fn main() {
    let amount = CustomType::<NaiveDate>::new("When are you going to visit the office?")
        .with_placeholder("dd/mm/yyyy")
        .with_parser(&|i| NaiveDate::parse_from_str(i, "%d/%m/%Y").map_err(|_| ()))
        .with_formatter(DEFAULT_DATE_FORMATTER)
        .with_error_message("Please type a valid date.")
        .with_help_message("The necessary arrangements will be made")
        .prompt();

    match amount {
        Ok(_) => println!("Thanks! We will be expecting you."),
        Err(_) => println!("We could not process your reservation"),
    }
}
More examples
Hide additional examples
examples/date.rs (line 26)
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
fn custom_type_parsed_date_prompt() {
    println!("-------> Date parsed from text input with Custom Type prompt");
    println!();

    let amount = CustomType::<NaiveDate>::new("When are you going to visit the office?")
        .with_placeholder("dd/mm/yyyy")
        .with_parser(&|i| NaiveDate::parse_from_str(i, "%d/%m/%Y").map_err(|_| ()))
        .with_formatter(DEFAULT_DATE_FORMATTER)
        .with_error_message("Please type a valid date.")
        .with_help_message("The necessary arrangements will be made")
        .prompt();

    match amount {
        Ok(_) => println!("Thanks! We will be expecting you."),
        Err(_) => println!("We could not process your reservation"),
    }
    println!();
}
source

pub fn with_help_message(self, message: &'a str) -> Self

Sets the help message of the prompt.

Examples found in repository?
examples/manual_date_input.rs (line 10)
4
5
6
7
8
9
10
11
12
13
14
15
16
17
fn main() {
    let amount = CustomType::<NaiveDate>::new("When are you going to visit the office?")
        .with_placeholder("dd/mm/yyyy")
        .with_parser(&|i| NaiveDate::parse_from_str(i, "%d/%m/%Y").map_err(|_| ()))
        .with_formatter(DEFAULT_DATE_FORMATTER)
        .with_error_message("Please type a valid date.")
        .with_help_message("The necessary arrangements will be made")
        .prompt();

    match amount {
        Ok(_) => println!("Thanks! We will be expecting you."),
        Err(_) => println!("We could not process your reservation"),
    }
}
More examples
Hide additional examples
examples/date.rs (line 30)
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
fn custom_type_parsed_date_prompt() {
    println!("-------> Date parsed from text input with Custom Type prompt");
    println!();

    let amount = CustomType::<NaiveDate>::new("When are you going to visit the office?")
        .with_placeholder("dd/mm/yyyy")
        .with_parser(&|i| NaiveDate::parse_from_str(i, "%d/%m/%Y").map_err(|_| ()))
        .with_formatter(DEFAULT_DATE_FORMATTER)
        .with_error_message("Please type a valid date.")
        .with_help_message("The necessary arrangements will be made")
        .prompt();

    match amount {
        Ok(_) => println!("Thanks! We will be expecting you."),
        Err(_) => println!("We could not process your reservation"),
    }
    println!();
}
examples/custom_type.rs (line 7)
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
fn main() {
    let amount = CustomType::<f64>::new("How much do you want to donate?")
        .with_formatter(&|i| format!("${i:.2}"))
        .with_error_message("Please type a valid number")
        .with_help_message("Type the amount in US dollars using a decimal point as a separator")
        .with_validator(|val: &f64| {
            if *val <= 0.0f64 {
                Ok(Validation::Invalid(
                    "You must donate a positive amount of dollars".into(),
                ))
            } else {
                Ok(Validation::Valid)
            }
        })
        .prompt();

    match amount {
        Ok(_) => println!("Thanks a lot for donating that much money!"),
        Err(_) => println!("We could not process your donation"),
    }
}
examples/expense_tracker.rs (line 23)
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
fn main() -> InquireResult<()> {
    let _date = DateSelect::new("Date:").prompt()?;

    let _category = Select::new("Category:", get_categories()).prompt()?;

    let _payee = Text::new("Payee:")
        .with_validator(required!("This field is required"))
        .with_autocomplete(&payee_suggestor)
        .with_help_message("e.g. Music Store")
        .with_page_size(5)
        .prompt()?;

    let amount: f64 = CustomType::new("Amount:")
        .with_formatter(&|i: f64| format!("${i}"))
        .with_error_message("Please type a valid number")
        .with_help_message("Type the amount in US dollars using a decimal point as a separator")
        .prompt()
        .unwrap();

    let _description = Text::new("Description:")
        .with_help_message("Optional notes")
        .prompt()?;

    let mut accounts = get_accounts();
    let accounts_mut = accounts.iter_mut().collect();
    let account = Select::new("Account:", accounts_mut).prompt()?;
    account.balance -= amount;

    let _tags = MultiSelect::new("Tags:", get_tags()).prompt()?;

    println!("Your transaction has been successfully recorded.");
    println!("The balance of {} is now ${:.2}", account, account.balance);

    Ok(())
}
examples/empty_render_config.rs (line 27)
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
fn main() -> InquireResult<()> {
    inquire::set_global_render_config(RenderConfig::empty());

    let _date = DateSelect::new("Date:").prompt()?;

    let _category = Select::new("Category:", get_categories()).prompt()?;

    let _payee = Text::new("Payee:")
        .with_validator(required!("This field is required"))
        .with_autocomplete(&payee_suggestor)
        .with_help_message("e.g. Music Store")
        .with_page_size(5)
        .prompt()?;

    let amount: f64 = CustomType::new("Amount:")
        .with_formatter(&|i: f64| format!("${i}"))
        .with_error_message("Please type a valid number")
        .with_help_message("Type the amount in US dollars using a decimal point as a separator")
        .prompt()
        .unwrap();

    let _description = Text::new("Description:")
        .with_help_message("Optional notes")
        .prompt()?;

    let mut accounts = get_accounts();
    let accounts_mut = accounts.iter_mut().collect();
    let account = Select::new("Account:", accounts_mut).prompt()?;
    account.balance -= amount;

    let _tags = MultiSelect::new("Tags:", get_tags()).prompt()?;

    println!("Your transaction has been successfully recorded.");
    println!("The balance of {account} is now $311.09");

    Ok(())
}
examples/render_config.rs (line 27)
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
fn main() -> InquireResult<()> {
    inquire::set_global_render_config(get_render_config());

    let _date = DateSelect::new("Date:").prompt()?;

    let _category = Select::new("Category:", get_categories()).prompt()?;

    let _payee = Text::new("Payee:")
        .with_validator(required!("This field is required"))
        .with_autocomplete(&payee_suggestor)
        .with_help_message("e.g. Music Store")
        .with_page_size(5)
        .prompt()?;

    let amount: f64 = CustomType::new("Amount:")
        .with_formatter(&|i: f64| format!("${i}"))
        .with_error_message("Please type a valid number")
        .with_help_message("Type the amount in US dollars using a decimal point as a separator")
        .prompt()
        .unwrap();

    let _description = Text::new("Description:")
        .with_help_message("Optional notes")
        .prompt()?;

    let mut accounts = get_accounts();
    let accounts_mut = accounts.iter_mut().collect();
    let account = Select::new("Account:", accounts_mut).prompt()?;
    account.balance -= amount;

    let _tags = MultiSelect::new("Tags:", get_tags()).prompt()?;

    println!("Your transaction has been successfully recorded.");
    println!(
        "The balance of {} is now ${:.2}",
        account.name, account.balance
    );

    Ok(())
}
source

pub fn with_formatter(self, formatter: CustomTypeFormatter<'a, T>) -> Self

Sets the formatter

Examples found in repository?
examples/manual_date_input.rs (line 8)
4
5
6
7
8
9
10
11
12
13
14
15
16
17
fn main() {
    let amount = CustomType::<NaiveDate>::new("When are you going to visit the office?")
        .with_placeholder("dd/mm/yyyy")
        .with_parser(&|i| NaiveDate::parse_from_str(i, "%d/%m/%Y").map_err(|_| ()))
        .with_formatter(DEFAULT_DATE_FORMATTER)
        .with_error_message("Please type a valid date.")
        .with_help_message("The necessary arrangements will be made")
        .prompt();

    match amount {
        Ok(_) => println!("Thanks! We will be expecting you."),
        Err(_) => println!("We could not process your reservation"),
    }
}
More examples
Hide additional examples
examples/date.rs (line 28)
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
fn custom_type_parsed_date_prompt() {
    println!("-------> Date parsed from text input with Custom Type prompt");
    println!();

    let amount = CustomType::<NaiveDate>::new("When are you going to visit the office?")
        .with_placeholder("dd/mm/yyyy")
        .with_parser(&|i| NaiveDate::parse_from_str(i, "%d/%m/%Y").map_err(|_| ()))
        .with_formatter(DEFAULT_DATE_FORMATTER)
        .with_error_message("Please type a valid date.")
        .with_help_message("The necessary arrangements will be made")
        .prompt();

    match amount {
        Ok(_) => println!("Thanks! We will be expecting you."),
        Err(_) => println!("We could not process your reservation"),
    }
    println!();
}
examples/custom_type.rs (line 5)
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
fn main() {
    let amount = CustomType::<f64>::new("How much do you want to donate?")
        .with_formatter(&|i| format!("${i:.2}"))
        .with_error_message("Please type a valid number")
        .with_help_message("Type the amount in US dollars using a decimal point as a separator")
        .with_validator(|val: &f64| {
            if *val <= 0.0f64 {
                Ok(Validation::Invalid(
                    "You must donate a positive amount of dollars".into(),
                ))
            } else {
                Ok(Validation::Valid)
            }
        })
        .prompt();

    match amount {
        Ok(_) => println!("Thanks a lot for donating that much money!"),
        Err(_) => println!("We could not process your donation"),
    }
}
examples/expense_tracker.rs (line 21)
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
fn main() -> InquireResult<()> {
    let _date = DateSelect::new("Date:").prompt()?;

    let _category = Select::new("Category:", get_categories()).prompt()?;

    let _payee = Text::new("Payee:")
        .with_validator(required!("This field is required"))
        .with_autocomplete(&payee_suggestor)
        .with_help_message("e.g. Music Store")
        .with_page_size(5)
        .prompt()?;

    let amount: f64 = CustomType::new("Amount:")
        .with_formatter(&|i: f64| format!("${i}"))
        .with_error_message("Please type a valid number")
        .with_help_message("Type the amount in US dollars using a decimal point as a separator")
        .prompt()
        .unwrap();

    let _description = Text::new("Description:")
        .with_help_message("Optional notes")
        .prompt()?;

    let mut accounts = get_accounts();
    let accounts_mut = accounts.iter_mut().collect();
    let account = Select::new("Account:", accounts_mut).prompt()?;
    account.balance -= amount;

    let _tags = MultiSelect::new("Tags:", get_tags()).prompt()?;

    println!("Your transaction has been successfully recorded.");
    println!("The balance of {} is now ${:.2}", account, account.balance);

    Ok(())
}
examples/empty_render_config.rs (line 25)
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
fn main() -> InquireResult<()> {
    inquire::set_global_render_config(RenderConfig::empty());

    let _date = DateSelect::new("Date:").prompt()?;

    let _category = Select::new("Category:", get_categories()).prompt()?;

    let _payee = Text::new("Payee:")
        .with_validator(required!("This field is required"))
        .with_autocomplete(&payee_suggestor)
        .with_help_message("e.g. Music Store")
        .with_page_size(5)
        .prompt()?;

    let amount: f64 = CustomType::new("Amount:")
        .with_formatter(&|i: f64| format!("${i}"))
        .with_error_message("Please type a valid number")
        .with_help_message("Type the amount in US dollars using a decimal point as a separator")
        .prompt()
        .unwrap();

    let _description = Text::new("Description:")
        .with_help_message("Optional notes")
        .prompt()?;

    let mut accounts = get_accounts();
    let accounts_mut = accounts.iter_mut().collect();
    let account = Select::new("Account:", accounts_mut).prompt()?;
    account.balance -= amount;

    let _tags = MultiSelect::new("Tags:", get_tags()).prompt()?;

    println!("Your transaction has been successfully recorded.");
    println!("The balance of {account} is now $311.09");

    Ok(())
}
examples/render_config.rs (line 25)
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
fn main() -> InquireResult<()> {
    inquire::set_global_render_config(get_render_config());

    let _date = DateSelect::new("Date:").prompt()?;

    let _category = Select::new("Category:", get_categories()).prompt()?;

    let _payee = Text::new("Payee:")
        .with_validator(required!("This field is required"))
        .with_autocomplete(&payee_suggestor)
        .with_help_message("e.g. Music Store")
        .with_page_size(5)
        .prompt()?;

    let amount: f64 = CustomType::new("Amount:")
        .with_formatter(&|i: f64| format!("${i}"))
        .with_error_message("Please type a valid number")
        .with_help_message("Type the amount in US dollars using a decimal point as a separator")
        .prompt()
        .unwrap();

    let _description = Text::new("Description:")
        .with_help_message("Optional notes")
        .prompt()?;

    let mut accounts = get_accounts();
    let accounts_mut = accounts.iter_mut().collect();
    let account = Select::new("Account:", accounts_mut).prompt()?;
    account.balance -= amount;

    let _tags = MultiSelect::new("Tags:", get_tags()).prompt()?;

    println!("Your transaction has been successfully recorded.");
    println!(
        "The balance of {} is now ${:.2}",
        account.name, account.balance
    );

    Ok(())
}
source

pub fn with_default_value_formatter( self, formatter: CustomTypeFormatter<'a, T> ) -> Self

Sets the formatter for default values.

Useful for example when you want to format a default true to the string “Y/n”, common in confirmation prompts, when the final answer would be displayed likely as “Yes” or “No”.

source

pub fn with_parser(self, parser: CustomTypeParser<'a, T>) -> Self

Sets the parser.

Examples found in repository?
examples/manual_date_input.rs (line 7)
4
5
6
7
8
9
10
11
12
13
14
15
16
17
fn main() {
    let amount = CustomType::<NaiveDate>::new("When are you going to visit the office?")
        .with_placeholder("dd/mm/yyyy")
        .with_parser(&|i| NaiveDate::parse_from_str(i, "%d/%m/%Y").map_err(|_| ()))
        .with_formatter(DEFAULT_DATE_FORMATTER)
        .with_error_message("Please type a valid date.")
        .with_help_message("The necessary arrangements will be made")
        .prompt();

    match amount {
        Ok(_) => println!("Thanks! We will be expecting you."),
        Err(_) => println!("We could not process your reservation"),
    }
}
More examples
Hide additional examples
examples/date.rs (line 27)
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
fn custom_type_parsed_date_prompt() {
    println!("-------> Date parsed from text input with Custom Type prompt");
    println!();

    let amount = CustomType::<NaiveDate>::new("When are you going to visit the office?")
        .with_placeholder("dd/mm/yyyy")
        .with_parser(&|i| NaiveDate::parse_from_str(i, "%d/%m/%Y").map_err(|_| ()))
        .with_formatter(DEFAULT_DATE_FORMATTER)
        .with_error_message("Please type a valid date.")
        .with_help_message("The necessary arrangements will be made")
        .prompt();

    match amount {
        Ok(_) => println!("Thanks! We will be expecting you."),
        Err(_) => println!("We could not process your reservation"),
    }
    println!();
}
source

pub fn with_validator<V>(self, validator: V) -> Selfwhere V: CustomTypeValidator<T> + 'static,

Adds a validator to the collection of validators. You might want to use this feature in case you need to require certain features from the parsed user’s answer.

Validators are executed in the order they are stored, stopping at and displaying to the user only the first validation error that might appear.

The possible error is displayed to the user one line above the prompt.

Examples found in repository?
examples/custom_type.rs (lines 8-16)
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
fn main() {
    let amount = CustomType::<f64>::new("How much do you want to donate?")
        .with_formatter(&|i| format!("${i:.2}"))
        .with_error_message("Please type a valid number")
        .with_help_message("Type the amount in US dollars using a decimal point as a separator")
        .with_validator(|val: &f64| {
            if *val <= 0.0f64 {
                Ok(Validation::Invalid(
                    "You must donate a positive amount of dollars".into(),
                ))
            } else {
                Ok(Validation::Valid)
            }
        })
        .prompt();

    match amount {
        Ok(_) => println!("Thanks a lot for donating that much money!"),
        Err(_) => println!("We could not process your donation"),
    }
}
source

pub fn with_validators( self, validators: &[Box<dyn CustomTypeValidator<T>>] ) -> Self

Adds the validators to the collection of validators in the order they are given. You might want to use this feature in case you need to require certain features from the parsed user’s answer.

Validators are executed in the order they are stored, stopping at and displaying to the user only the first validation error that might appear.

The possible error is displayed to the user one line above the prompt.

source

pub fn with_error_message(self, error_message: &'a str) -> Self

Sets a custom error message displayed when a submission could not be parsed to a value.

Examples found in repository?
examples/manual_date_input.rs (line 9)
4
5
6
7
8
9
10
11
12
13
14
15
16
17
fn main() {
    let amount = CustomType::<NaiveDate>::new("When are you going to visit the office?")
        .with_placeholder("dd/mm/yyyy")
        .with_parser(&|i| NaiveDate::parse_from_str(i, "%d/%m/%Y").map_err(|_| ()))
        .with_formatter(DEFAULT_DATE_FORMATTER)
        .with_error_message("Please type a valid date.")
        .with_help_message("The necessary arrangements will be made")
        .prompt();

    match amount {
        Ok(_) => println!("Thanks! We will be expecting you."),
        Err(_) => println!("We could not process your reservation"),
    }
}
More examples
Hide additional examples
examples/date.rs (line 29)
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
fn custom_type_parsed_date_prompt() {
    println!("-------> Date parsed from text input with Custom Type prompt");
    println!();

    let amount = CustomType::<NaiveDate>::new("When are you going to visit the office?")
        .with_placeholder("dd/mm/yyyy")
        .with_parser(&|i| NaiveDate::parse_from_str(i, "%d/%m/%Y").map_err(|_| ()))
        .with_formatter(DEFAULT_DATE_FORMATTER)
        .with_error_message("Please type a valid date.")
        .with_help_message("The necessary arrangements will be made")
        .prompt();

    match amount {
        Ok(_) => println!("Thanks! We will be expecting you."),
        Err(_) => println!("We could not process your reservation"),
    }
    println!();
}
examples/custom_type.rs (line 6)
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
fn main() {
    let amount = CustomType::<f64>::new("How much do you want to donate?")
        .with_formatter(&|i| format!("${i:.2}"))
        .with_error_message("Please type a valid number")
        .with_help_message("Type the amount in US dollars using a decimal point as a separator")
        .with_validator(|val: &f64| {
            if *val <= 0.0f64 {
                Ok(Validation::Invalid(
                    "You must donate a positive amount of dollars".into(),
                ))
            } else {
                Ok(Validation::Valid)
            }
        })
        .prompt();

    match amount {
        Ok(_) => println!("Thanks a lot for donating that much money!"),
        Err(_) => println!("We could not process your donation"),
    }
}
examples/expense_tracker.rs (line 22)
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
fn main() -> InquireResult<()> {
    let _date = DateSelect::new("Date:").prompt()?;

    let _category = Select::new("Category:", get_categories()).prompt()?;

    let _payee = Text::new("Payee:")
        .with_validator(required!("This field is required"))
        .with_autocomplete(&payee_suggestor)
        .with_help_message("e.g. Music Store")
        .with_page_size(5)
        .prompt()?;

    let amount: f64 = CustomType::new("Amount:")
        .with_formatter(&|i: f64| format!("${i}"))
        .with_error_message("Please type a valid number")
        .with_help_message("Type the amount in US dollars using a decimal point as a separator")
        .prompt()
        .unwrap();

    let _description = Text::new("Description:")
        .with_help_message("Optional notes")
        .prompt()?;

    let mut accounts = get_accounts();
    let accounts_mut = accounts.iter_mut().collect();
    let account = Select::new("Account:", accounts_mut).prompt()?;
    account.balance -= amount;

    let _tags = MultiSelect::new("Tags:", get_tags()).prompt()?;

    println!("Your transaction has been successfully recorded.");
    println!("The balance of {} is now ${:.2}", account, account.balance);

    Ok(())
}
examples/empty_render_config.rs (line 26)
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
fn main() -> InquireResult<()> {
    inquire::set_global_render_config(RenderConfig::empty());

    let _date = DateSelect::new("Date:").prompt()?;

    let _category = Select::new("Category:", get_categories()).prompt()?;

    let _payee = Text::new("Payee:")
        .with_validator(required!("This field is required"))
        .with_autocomplete(&payee_suggestor)
        .with_help_message("e.g. Music Store")
        .with_page_size(5)
        .prompt()?;

    let amount: f64 = CustomType::new("Amount:")
        .with_formatter(&|i: f64| format!("${i}"))
        .with_error_message("Please type a valid number")
        .with_help_message("Type the amount in US dollars using a decimal point as a separator")
        .prompt()
        .unwrap();

    let _description = Text::new("Description:")
        .with_help_message("Optional notes")
        .prompt()?;

    let mut accounts = get_accounts();
    let accounts_mut = accounts.iter_mut().collect();
    let account = Select::new("Account:", accounts_mut).prompt()?;
    account.balance -= amount;

    let _tags = MultiSelect::new("Tags:", get_tags()).prompt()?;

    println!("Your transaction has been successfully recorded.");
    println!("The balance of {account} is now $311.09");

    Ok(())
}
examples/render_config.rs (line 26)
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
fn main() -> InquireResult<()> {
    inquire::set_global_render_config(get_render_config());

    let _date = DateSelect::new("Date:").prompt()?;

    let _category = Select::new("Category:", get_categories()).prompt()?;

    let _payee = Text::new("Payee:")
        .with_validator(required!("This field is required"))
        .with_autocomplete(&payee_suggestor)
        .with_help_message("e.g. Music Store")
        .with_page_size(5)
        .prompt()?;

    let amount: f64 = CustomType::new("Amount:")
        .with_formatter(&|i: f64| format!("${i}"))
        .with_error_message("Please type a valid number")
        .with_help_message("Type the amount in US dollars using a decimal point as a separator")
        .prompt()
        .unwrap();

    let _description = Text::new("Description:")
        .with_help_message("Optional notes")
        .prompt()?;

    let mut accounts = get_accounts();
    let accounts_mut = accounts.iter_mut().collect();
    let account = Select::new("Account:", accounts_mut).prompt()?;
    account.balance -= amount;

    let _tags = MultiSelect::new("Tags:", get_tags()).prompt()?;

    println!("Your transaction has been successfully recorded.");
    println!(
        "The balance of {} is now ${:.2}",
        account.name, account.balance
    );

    Ok(())
}
source

pub fn with_render_config(self, render_config: RenderConfig<'a>) -> Self

Sets the provided color theme to this prompt.

Note: The default render config considers if the NO_COLOR environment variable is set to decide whether to render the colored config or the empty one.

When overriding the config in a prompt, NO_COLOR is no longer considered and your config is treated as the only source of truth. If you want to customize colors and still suport NO_COLOR, you will have to do this on your end.

source

pub fn prompt_skippable(self) -> InquireResult<Option<T>>

Parses the provided behavioral and rendering options and prompts the CLI user for input according to the defined rules.

This method is intended for flows where the user skipping/cancelling the prompt - by pressing ESC - is considered normal behavior. In this case, it does not return Err(InquireError::OperationCanceled), but Ok(None).

Meanwhile, if the user does submit an answer, the method wraps the return type with Some.

source

pub fn prompt(self) -> InquireResult<T>

Parses the provided behavioral and rendering options and prompts the CLI user for input according to the defined rules.

Examples found in repository?
examples/manual_date_input.rs (line 11)
4
5
6
7
8
9
10
11
12
13
14
15
16
17
fn main() {
    let amount = CustomType::<NaiveDate>::new("When are you going to visit the office?")
        .with_placeholder("dd/mm/yyyy")
        .with_parser(&|i| NaiveDate::parse_from_str(i, "%d/%m/%Y").map_err(|_| ()))
        .with_formatter(DEFAULT_DATE_FORMATTER)
        .with_error_message("Please type a valid date.")
        .with_help_message("The necessary arrangements will be made")
        .prompt();

    match amount {
        Ok(_) => println!("Thanks! We will be expecting you."),
        Err(_) => println!("We could not process your reservation"),
    }
}
More examples
Hide additional examples
examples/date.rs (line 31)
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
fn custom_type_parsed_date_prompt() {
    println!("-------> Date parsed from text input with Custom Type prompt");
    println!();

    let amount = CustomType::<NaiveDate>::new("When are you going to visit the office?")
        .with_placeholder("dd/mm/yyyy")
        .with_parser(&|i| NaiveDate::parse_from_str(i, "%d/%m/%Y").map_err(|_| ()))
        .with_formatter(DEFAULT_DATE_FORMATTER)
        .with_error_message("Please type a valid date.")
        .with_help_message("The necessary arrangements will be made")
        .prompt();

    match amount {
        Ok(_) => println!("Thanks! We will be expecting you."),
        Err(_) => println!("We could not process your reservation"),
    }
    println!();
}
examples/custom_type.rs (line 17)
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
fn main() {
    let amount = CustomType::<f64>::new("How much do you want to donate?")
        .with_formatter(&|i| format!("${i:.2}"))
        .with_error_message("Please type a valid number")
        .with_help_message("Type the amount in US dollars using a decimal point as a separator")
        .with_validator(|val: &f64| {
            if *val <= 0.0f64 {
                Ok(Validation::Invalid(
                    "You must donate a positive amount of dollars".into(),
                ))
            } else {
                Ok(Validation::Valid)
            }
        })
        .prompt();

    match amount {
        Ok(_) => println!("Thanks a lot for donating that much money!"),
        Err(_) => println!("We could not process your donation"),
    }
}
examples/expense_tracker.rs (line 24)
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
fn main() -> InquireResult<()> {
    let _date = DateSelect::new("Date:").prompt()?;

    let _category = Select::new("Category:", get_categories()).prompt()?;

    let _payee = Text::new("Payee:")
        .with_validator(required!("This field is required"))
        .with_autocomplete(&payee_suggestor)
        .with_help_message("e.g. Music Store")
        .with_page_size(5)
        .prompt()?;

    let amount: f64 = CustomType::new("Amount:")
        .with_formatter(&|i: f64| format!("${i}"))
        .with_error_message("Please type a valid number")
        .with_help_message("Type the amount in US dollars using a decimal point as a separator")
        .prompt()
        .unwrap();

    let _description = Text::new("Description:")
        .with_help_message("Optional notes")
        .prompt()?;

    let mut accounts = get_accounts();
    let accounts_mut = accounts.iter_mut().collect();
    let account = Select::new("Account:", accounts_mut).prompt()?;
    account.balance -= amount;

    let _tags = MultiSelect::new("Tags:", get_tags()).prompt()?;

    println!("Your transaction has been successfully recorded.");
    println!("The balance of {} is now ${:.2}", account, account.balance);

    Ok(())
}
examples/empty_render_config.rs (line 28)
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
fn main() -> InquireResult<()> {
    inquire::set_global_render_config(RenderConfig::empty());

    let _date = DateSelect::new("Date:").prompt()?;

    let _category = Select::new("Category:", get_categories()).prompt()?;

    let _payee = Text::new("Payee:")
        .with_validator(required!("This field is required"))
        .with_autocomplete(&payee_suggestor)
        .with_help_message("e.g. Music Store")
        .with_page_size(5)
        .prompt()?;

    let amount: f64 = CustomType::new("Amount:")
        .with_formatter(&|i: f64| format!("${i}"))
        .with_error_message("Please type a valid number")
        .with_help_message("Type the amount in US dollars using a decimal point as a separator")
        .prompt()
        .unwrap();

    let _description = Text::new("Description:")
        .with_help_message("Optional notes")
        .prompt()?;

    let mut accounts = get_accounts();
    let accounts_mut = accounts.iter_mut().collect();
    let account = Select::new("Account:", accounts_mut).prompt()?;
    account.balance -= amount;

    let _tags = MultiSelect::new("Tags:", get_tags()).prompt()?;

    println!("Your transaction has been successfully recorded.");
    println!("The balance of {account} is now $311.09");

    Ok(())
}
examples/render_config.rs (line 28)
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
fn main() -> InquireResult<()> {
    inquire::set_global_render_config(get_render_config());

    let _date = DateSelect::new("Date:").prompt()?;

    let _category = Select::new("Category:", get_categories()).prompt()?;

    let _payee = Text::new("Payee:")
        .with_validator(required!("This field is required"))
        .with_autocomplete(&payee_suggestor)
        .with_help_message("e.g. Music Store")
        .with_page_size(5)
        .prompt()?;

    let amount: f64 = CustomType::new("Amount:")
        .with_formatter(&|i: f64| format!("${i}"))
        .with_error_message("Please type a valid number")
        .with_help_message("Type the amount in US dollars using a decimal point as a separator")
        .prompt()
        .unwrap();

    let _description = Text::new("Description:")
        .with_help_message("Optional notes")
        .prompt()?;

    let mut accounts = get_accounts();
    let accounts_mut = accounts.iter_mut().collect();
    let account = Select::new("Account:", accounts_mut).prompt()?;
    account.balance -= amount;

    let _tags = MultiSelect::new("Tags:", get_tags()).prompt()?;

    println!("Your transaction has been successfully recorded.");
    println!(
        "The balance of {} is now ${:.2}",
        account.name, account.balance
    );

    Ok(())
}

Trait Implementations§

source§

impl<'a, T: Clone> Clone for CustomType<'a, T>

source§

fn clone(&self) -> CustomType<'a, T>

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl<'a> From<Confirm<'a>> for CustomType<'a, bool>

source§

fn from(co: Confirm<'a>) -> Self

Converts to this type from the input type.

Auto Trait Implementations§

§

impl<'a, T> !RefUnwindSafe for CustomType<'a, T>

§

impl<'a, T> !Send for CustomType<'a, T>

§

impl<'a, T> !Sync for CustomType<'a, T>

§

impl<'a, T> Unpin for CustomType<'a, T>where T: Unpin,

§

impl<'a, T> !UnwindSafe for CustomType<'a, T>

Blanket Implementations§

source§

impl<T> Any for Twhere T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for Twhere T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for Twhere T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> DynClone for Twhere T: Clone,

source§

fn __clone_box(&self, _: Private) -> *mut ()

source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for Twhere U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T> ToOwned for Twhere T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T, U> TryFrom<U> for Twhere U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for Twhere U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.