TextPrompt

Prompt users for text input with validation and default values

The TextPrompt prompts users to enter text input with validation, default values, and secret input masking.

When to Use

Use TextPrompt when you need to collect user input from the console. Common scenarios:

  • Free-form text input: Collecting names, email addresses, or any text data
  • Numeric input: Getting ages, quantities, or measurements with automatic type conversion
  • Secure input: Requesting passwords or API keys with masked display
  • Validated input: Ensuring input meets specific requirements before accepting it

For selecting from a predefined list of options, use SelectionPrompt instead, which provides a better user experience with arrow key navigation.

Caution

Text prompts are not thread safe. Using them together with other interactive components such as progress displays, status displays, or other prompts is not supported.

Basic Usage

Use AnsiConsole.Ask<T>() for the simplest way to prompt for user input.

csharp
var name = AnsiConsole.Ask<string>("What's your [green]name[/]?");
AnsiConsole.MarkupLine($"Hello, [blue]{name}[/]!");

Default Values

Using Ask with Default

You can provide a default value that users can accept by pressing Enter.

csharp
var name = AnsiConsole.Ask("What's your [green]name[/]?", "Anonymous");
AnsiConsole.MarkupLine($"Hello, [blue]{name}[/]!");

Configuring Default Display

Use DefaultValue() to set a default and control whether it's shown to the user.

csharp
var name = new TextPrompt<string>("What's your [green]name[/]?")
    .DefaultValue("Anonymous")
    .ShowDefaultValue();
  
var result = AnsiConsole.Prompt(name);
  
AnsiConsole.MarkupLine($"Hello, [blue]{result}[/]!");

Type Conversion

TextPrompt automatically converts input to your target type using built-in type converters.

csharp
var age = AnsiConsole.Ask<int>("What's your [green]age[/]?");
var height = AnsiConsole.Ask<decimal>("What's your [green]height[/] in meters?");
  
AnsiConsole.MarkupLine($"You are [blue]{age}[/] years old and [blue]{height}m[/] tall.");

This works with any type that has a TypeConverter, including int, decimal, DateTime, Guid, and custom types.

Direct TextPrompt Usage

For more control over prompt behavior, create a TextPrompt<T> instance directly instead of using Ask().

csharp
var prompt = new TextPrompt<string>("What's your [green]name[/]?");
var name = AnsiConsole.Prompt(prompt);
  
AnsiConsole.MarkupLine($"Hello, [blue]{name}[/]!");

Secret Input

Password Masking

Use Secret() to mask sensitive input with asterisks by default.

csharp
var password = new TextPrompt<string>("Enter your [green]password[/]:")
    .Secret();
  
var result = AnsiConsole.Prompt(password);
  
AnsiConsole.MarkupLine($"Password length: [blue]{result.Length}[/] characters");

Custom Mask Characters

Specify a custom mask character or use null to completely hide input.

csharp
var pin = new TextPrompt<string>("Enter your [green]PIN[/]:")
    .Secret('#');
  
var invisible = new TextPrompt<string>("Enter [green]secret code[/]:")
    .Secret(null);
  
var pinResult = AnsiConsole.Prompt(pin);
var codeResult = AnsiConsole.Prompt(invisible);
  
AnsiConsole.MarkupLine($"PIN entered (length: [blue]{pinResult.Length}[/])");
AnsiConsole.MarkupLine($"Code entered (length: [blue]{codeResult.Length}[/])");

Validation

Simple Validation

Use Validate() with a boolean function to check if input is acceptable.

csharp
var email = new TextPrompt<string>("What's your [green]email[/]?")
    .Validate(input =>
        input.Contains("@") && input.Contains("."),
        "[red]Please enter a valid email address[/]");
  
var result = AnsiConsole.Prompt(email);
  
AnsiConsole.MarkupLine($"Email: [blue]{result}[/]");

Rich Validation

For more complex validation with custom error messages, use ValidationResult.

csharp
var age = new TextPrompt<int>("What's your [green]age[/]?")
    .Validate(age =>
    {
        if (age < 0)
        {
            return ValidationResult.Error("[red]Age cannot be negative[/]");
        }
  
        if (age > 120)
        {
            return ValidationResult.Error("[red]Please enter a realistic age[/]");
        }
  
        if (age < 18)
        {
            return ValidationResult.Error("[yellow]You must be 18 or older[/]");
        }
  
        return ValidationResult.Success();
    });
  
var result = AnsiConsole.Prompt(age);
  
AnsiConsole.MarkupLine($"Age: [blue]{result}[/]");

Restricting to Choices

Showing Choices

Use AddChoices() to restrict input to specific values, displayed as options to the user.

csharp
var color = new TextPrompt<string>("What's your favorite [green]color[/]?")
    .AddChoice("red")
    .AddChoice("green")
    .AddChoice("blue")
    .AddChoice("yellow")
    .ShowChoices();
  
var result = AnsiConsole.Prompt(color);
  
AnsiConsole.MarkupLine($"You chose: [blue]{result}[/]");

This is useful for limited options where users can type their choice. For better UX with many options, use SelectionPrompt instead.

Hidden Choices

Use HideChoices() when you want to validate against specific values without revealing them.

csharp
var secretWord = new TextPrompt<string>("Enter the [green]secret word[/]:")
    .AddChoice("opensesame")
    .AddChoice("abracadabra")
    .AddChoice("alakazam")
    .HideChoices();
  
var result = AnsiConsole.Prompt(secretWord);
  
AnsiConsole.MarkupLine($"Correct! The word was: [blue]{result}[/]");

Optional Input

Use AllowEmpty() to make input optional, allowing users to press Enter without typing anything.

csharp
var nickname = new TextPrompt<string>("Enter your [green]nickname[/] (optional):")
    .AllowEmpty();
  
var result = AnsiConsole.Prompt(nickname);
  
if (string.IsNullOrWhiteSpace(result))
{
    AnsiConsole.MarkupLine("[yellow]No nickname provided[/]");
}
else
{
    AnsiConsole.MarkupLine($"Nickname: [blue]{result}[/]");
}

Styling

Customize the appearance of your prompts with different colors for the prompt text, default values, and choices.

csharp
var city = new TextPrompt<string>("What [yellow]city[/] do you live in?")
    .PromptStyle(new Style(Color.Yellow))
    .DefaultValue("London")
    .DefaultValueStyle(new Style(Color.Green, decoration: Decoration.Italic))
    .AddChoice("London")
    .AddChoice("New York")
    .AddChoice("Tokyo")
    .AddChoice("Paris")
    .ChoicesStyle(new Style(Color.Cyan));
  
var result = AnsiConsole.Prompt(city);
  
AnsiConsole.MarkupLine($"City: [blue]{result}[/]");

Custom Converters

Use WithConverter() to control how choices are displayed to users while keeping their underlying values.

csharp
var priority = new TextPrompt<int>("Select [green]priority[/] level:")
    .AddChoice(1)
    .AddChoice(2)
    .AddChoice(3)
    .AddChoice(4)
    .AddChoice(5)
    .WithConverter(level => level switch
    {
        1 => "Critical",
        2 => "High",
        3 => "Medium",
        4 => "Low",
        5 => "Trivial",
        _ => level.ToString()
    });
  
var result = AnsiConsole.Prompt(priority);
  
AnsiConsole.MarkupLine($"Priority level: [blue]{result}[/]");

See Also

API Reference

Represents a prompt.

Constructors

public TextPrompt`1(string prompt, StringComparer comparer = null)

Initializes a new instance of the TextPrompt class.

Parameters:

prompt (string)
The prompt markup text.
comparer (StringComparer)
The comparer used for choices.

Properties

AllowEmpty : bool

Gets or sets a value indicating whether or not an empty result is valid.

Choices : List<T>

Gets the list of choices.

ClearOnFinish : bool

Gets or sets a value indicating whether the prompt line should be cleared after a successful input.

Converter : Func<T, string>

Gets or sets the converter to get the display string for a choice. By default the corresponding TypeConverter is used.

Culture : CultureInfo

Gets or sets the culture to use when converting input to object.

EditableDefaultValue : bool

Gets or sets the default value editable state that allows the injection of the DefaultValue in the text field. If true this places the DefaultValue in the input buffer which can then be edited by the user.

InvalidChoiceMessage : string

Gets or sets the message for invalid choices.

IsSecret : bool

Gets or sets a value indicating whether input should be hidden in the console.

Mask : char?

Gets or sets the character to use while masking a secret prompt.

ShowChoices : bool

Gets or sets a value indicating whether or not choices should be shown.

ShowDefaultValue : bool

Gets or sets a value indicating whether or not default values should be shown.

ValidationErrorMessage : string

Gets or sets the validation error message.

Validator : Func<T, ValidationResult>

Gets or sets the validator.

Methods

public T Show(IAnsiConsole console)

Shows the prompt and requests input from the user.

Parameters:

console (IAnsiConsole)
The console to show the prompt in.

Returns:

The user input converted to the expected type.

public Task<T> ShowAsync(IAnsiConsole console, CancellationToken cancellationToken)

Shows the prompt asynchronously.

Parameters:

console (IAnsiConsole)
The console.
cancellationToken (CancellationToken)
The token to monitor for cancellation requests.

Returns:

The prompt input result.

Extension Methods

TextPrompt<T> AllowEmpty<T>(this TextPrompt<T> obj)

Allow empty input.

Returns:

The same instance so that multiple calls can be chained.