我正在使用此处找到的表单流示例
该示例使用 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;
}