在 formFlow 中添加验证步骤 - 检查浇头是否有货

Adding verification step in formFlow - Check if topping is in stock

我正在使用找到的表单流程示例 Here

该示例使用 formFlow 帮助用户挑选他们想要的三明治配料。

我正在尝试添加一个验证步骤,检查他们添加的每种配料是否有货,如果没有,则发送道歉消息并提示用户输入不同的配料。下面是一个代码示例:

public static IForm<SandwichOrder> BuildForm()
{

return new FormBuilder<SandwichOrder>()
    .Message("Welcome to the sandwich order bot!")
    .Field(nameof(Sandwich))
    .Field(nameof(Length))
    .Field(nameof(Bread))
    .Field(nameof(Cheese))
    .Field(nameof(Topping),
        validate: async (state, value) =>
        {
            foreach(var t in Topping)
            {
                if (!isToppinginStock)
                {
                    // Apology message
                    //Code to ask topping question again
                }
            }


        })
    .Message("For sandwich toppings you have selected {Toppings}.")

    .Build();
   }

如果有人能帮助我或指出正确的方向,我将不胜感激。

类似下面的内容应该适用于您的场景:

.Field(nameof(Toppings),
    validate: async (state, value) =>
    {
        var values = ((List<object>)value).OfType<ToppingOptions>();
        var notInStock = GetOutOfStockToppings(values);

        if(notInStock.Any())
            return new ValidateResult { IsValid = false, Value = null, Feedback = $"These are not in stock: {string.Join(",", notInStock.ToArray())} Please choose again." };

        return new ValidateResult { IsValid = true, Value = values};
    })

static IEnumerable<ToppingOptions> NotInStock = new[] { ToppingOptions.Lettuce, ToppingOptions.Pickles };
private static IEnumerable<ToppingOptions> GetOutOfStockToppings(IEnumerable<ToppingOptions> toppings)
{
    List<ToppingOptions> result = new List<ToppingOptions>();
    foreach(var topping in toppings)
    {
        if (NotInStock.Contains(topping))
            result.Add(topping);
    }
    return result;
}