c# 自适应卡模板中的客户端验证

client side validation in adaptive cards templating in c#

输入类型等基本验证不适用于模拟器或网络聊天。我在 bot 框架和自适应卡 v1.2 模板中使用 .net 核心。像 isRequired 和 errorMessage 这样的验证在自适应卡片 v1.3 中可用,但在网络聊天中不支持。如何在自适应卡片中获得客户端验证?

您可以使用一些技巧来使 client-side 验证在网络聊天中起作用,如以下答案所示:

While examining the source code for version 1.2.6, I came across some secret required-input code that was probably just meant for testing purposes but actually does work in Web Chat. That proto-schema looks like this:

{
  "type": "Input.Text",
  "id": "firstName",
  "placeholder": "First Name",
  "validation": {
    "necessity": "Required",
    "errorMessage": "First Name is required"
  }
}

If that works for you then great, but if you want more control or if you happen to be using an even earlier version of Adaptive Cards then you'll need the rest of this answer.

When you talk about making an input field "required" it seems like you want these two behaviors when a submit action is clicked and the field is empty:

  1. You want the submit action to not be processed
  2. You want an error message to be displayed

Web Chat specifies an action handler for each Adaptive Card it creates and there's no easy way to override that, so for behavior #1 your best option is to have your bot check the incoming inputs and short-circuit its logic if a required input is missing.

For behavior #2, you could also handle that on the bot side by having the bot send a message back to Web Chat that lets the user know which inputs are missing from the Adaptive Card. Alternatively, you could send a new card with an additional text block next to each input field that wasn't populated in the first card.

If you really want to toggle those text blocks on the Web Chat side then there may actually be a way to do that. Even if you can't override Web Chat's submit action behavior, you can add to the behavior by providing an onExecute handler for each action. You'll have to read this answer for an explanation of how to apply special Adaptive Card functionality in Web Chat: