ChoicePrompt, how to always call the validator in Botframework v4

BotFramework v4 has a number of helper prompts, TextPrompt, ChoicePrompt, etc. One common mechanism they share is a Validator delegate. When the user enters a value the Validator is invoked and you have an opportunity to check/change the outcome

var obj = new ValidatingTextPrompt(async (context, toValidate) =>
    {
        if (toValidate.Text.Length < minimumLength)
        {
            toValidate.Status = null;
            await context.SendActivity(minimumLengthMessage);
        }
    }
    );

The presence of the RetryPromptString means the ChoicePrompt will automatically retry of the user enters the incorrect value, such as 'frog'. However, what happens if the user enters the value '3'? Unfortunately this is considered as the 3rd choice and 'quit' will be selected. If your UI is really serving up numbers like this, that could be a real problem. Imagine if the list was 2,4,6 and you entered '3' or even worse '2'!? So I really want to add a Validator delegate that all prompts support;

this.Dialogs.Add("choicePrompt", new ChoicePrompt(Culture.English, ValidateChoice));

private async Task ValidateChoice(ITurnContext context, ChoiceResult toValidate)
{
    var userMessage = context.Activity.Text;
    if (userMessage == "3")
    {
        toValidate.Status = null;
        await Task.Delay(1);
    }
}

Sorted right? Wrong. Unfortunately there are two problems with this solutions; a) this is only called when a value from the choices list is selected (really??) b) the resulting selected value is passed in and not the original, i.e. ‘quit’ is passed in rather than ‘3’. My solution is to derive a new ChoicePrompt that will always call the available Validator with the original values;

public class ChoicePromptAlwaysVerify : Microsoft.Bot.Builder.Dialogs.ChoicePrompt
{
    private readonly PromptValidatorEx.PromptValidator validator;

    public ChoicePromptAlwaysVerify(string culture, PromptValidatorEx.PromptValidator validator = null) : base(culture, validator)
    {
        this.validator = validator;
    }

    protected override async Task OnRecognize(DialogContext dc, PromptOptions options)
    {
        var recognize = await base.OnRecognize(dc, options);
        if (this.validator != null)
        {
            await this.validator.Invoke(dc.Context, recognize);
        }

        return recognize;
    }
}

The code works by forcing the recognize override to call the validator. The downside is that this code will be called twice when the user makes a good choice (sigh), but it’s a small sacrifice to regain some consistent control over the valid values. It also allows for more specialized messages as the RetryMessage is fixed and has no chance to give a contextual response.

Advertisements