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.

Basic Usage

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

public static void BasicAskExample()
{
    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.

public static void AskWithDefaultExample()
{
    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.

public static void DefaultValueExample()
{
    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.

public static void TypeConversionExample()
{
    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().

public static void TextPromptBasicExample()
{
    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.

public static void SecretInputExample()
{
    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.

public static void CustomMaskExample()
{
    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.

public static void SimpleValidationExample()
{
    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.

public static void RichValidationExample()
{
    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.

public static void ChoicesExample()
{
    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.

public static void HiddenChoicesExample()
{
    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.

public static void AllowEmptyExample()
{
    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.

public static void StylingExample()
{
    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.

public static void CustomConverterExample()
{
    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}[/]");
}

API Reference

Represents a prompt.

Constructors

TextPrompt`1(string prompt, StringComparer comparer)

Initializes a new instance of the 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.

ChoicesStyle : Style

Gets or sets the style in which the list of choices is displayed. Defaults to blue when .

Converter : Func<T, string>

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

Culture : CultureInfo

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

DefaultValueStyle : Style

Gets or sets the style in which the default value is displayed. Defaults to green when .

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 : Nullable<Char>

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

PromptStyle : Style

Gets or sets the prompt style.

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

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.

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

Parameters:

console (IAnsiConsole)
cancellationToken (CancellationToken)