如何验证Microsoft聊天机器人中AdaptiveCard的TextInput控件?
完善Adaptive Card TextInput验证的方案
针对你在Microsoft Bot Framework中使用Adaptive Card收集用户信息时的验证需求,我整理了几种更完善的实现方案,结合前端Adaptive Card自带能力和后端C#规范验证机制,能覆盖从即时反馈到安全校验的全场景:
1. 利用Adaptive Card自身的前端验证(无需后端交互)
Adaptive Card的TextInput控件本身支持内置验证规则,能在用户提交前就给出即时反馈,大幅提升交互体验:
IsRequired:标记字段为必填,提交时空值会触发默认提示Style:指定输入风格(如Email/Tel),客户端会自动匹配对应格式验证Pattern:自定义正则表达式,精准控制输入格式ErrorMessage:自定义验证失败时显示的提示文本
修改你的Adaptive Card代码,加入这些验证规则:
var card = new AdaptiveCard() { Body = new List<CardElement>() { new TextBlock() { Text = "Email" }, new TextInput() { Id = "Email", Placeholder = "Enter your email", Style = TextInputStyle.Email, IsRequired = true, // 自定义邮箱正则(也可依赖Style自带验证) Pattern = @"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$", ErrorMessage = "Please enter a valid email address" }, new TextBlock() { Text = "Mobile" }, new TextInput() { Id = "Mobile", Placeholder = "+(country code)(Your Phone Number)", Style = TextInputStyle.Tel, IsRequired = true, // 国际手机号正则示例 Pattern = @"^\+[1-9]\d{1,14}$", ErrorMessage = "Please enter a valid international phone number (e.g., +1234567890)" }, }, Actions = new List<ActionBase>() { new SubmitAction() { Title = "Submit" } } }; Attachment attachment = new Attachment() { ContentType = AdaptiveCard.ContentType, Content = card };
2. 后端C#使用DataAnnotations属性验证
在后端,你可以借助.NET的DataAnnotations特性给PersonalInfo类添加标准化验证规则,让验证逻辑更可复用、更规范:
首先更新你的PersonalInfo类:
using System.ComponentModel.DataAnnotations; public class PersonalInfo { [Required(ErrorMessage = "Email is required")] [EmailAddress(ErrorMessage = "Please enter a valid email address")] public string Email { get; set; } [Required(ErrorMessage = "Phone number is required")] [Phone(ErrorMessage = "Please enter a valid phone number")] public string Phone { get; set; } }
然后修改GetErrorMessage方法,用Validator类自动执行验证:
using System.ComponentModel.DataAnnotations; using System.Collections.Generic; public string GetErrorMessage(PersonalInfo personalInfo) { var validationContext = new ValidationContext(personalInfo); var validationResults = new List<ValidationResult>(); bool isValid = Validator.TryValidateObject(personalInfo, validationContext, validationResults, validateAllProperties: true); if (!isValid) { // 拼接所有错误信息为可读性强的文本 return string.Join("\n", validationResults.Select(r => r.ErrorMessage)); } return string.Empty; }
3. 前端+后端的完整验证流程
前端验证可以提升用户体验,但可能被绕过,所以建议结合两者:
- 前端用Adaptive Card内置规则做即时校验,减少无效提交
- 后端用DataAnnotations做最终校验,确保数据合规性
在MessageReceivedAsync中,你可以保留现有逻辑,同时优化错误反馈方式:
protected async Task MessageReceivedAsync(IDialogContext context, IAwaitable<IMessageActivity> result) { var message = await result; PersonalInfo userinfo = new PersonalInfo(); if (message.Value != null) { dynamic formvalue = message.Value; if (formvalue != null) { userinfo.Email = GetValue((JObject)formvalue, "Email"); userinfo.Phone = GetValue((JObject)formvalue, "Mobile"); var error = GetErrorMessage(userinfo); IMessageActivity replyMessage = context.MakeMessage(); if (!string.IsNullOrEmpty(error)) { replyMessage.Text = $"Oops, we found some issues:\n{error}"; // 可选:重新发送Adaptive Card让用户直接修正 // replyMessage.Attachments = new List<Attachment> { attachment }; await context.PostAsync(replyMessage); } else { // 保存到服务总线的逻辑 if (!string.IsNullOrEmpty(sbConnectionString) && !string.IsNullOrEmpty(queueName)) await MainAsync(sbConnectionString, queueName, userinfo); replyMessage.Text = "Thank you for taking the time! \n We've submitted your query and an agent will get back to you soon. \n\n Have a great day!"; await context.PostAsync(replyMessage); context.Done(true); } } } }
额外优化:自定义复杂验证
如果需要更特殊的验证逻辑(比如手机号和地区绑定、字段间关联校验),可以在GetErrorMessage中添加自定义判断:
public string GetErrorMessage(PersonalInfo personalInfo) { var validationContext = new ValidationContext(personalInfo); var validationResults = new List<ValidationResult>(); bool isValid = Validator.TryValidateObject(personalInfo, validationContext, validationResults, validateAllProperties: true); // 自定义验证:手机号长度检查示例 if (!string.IsNullOrEmpty(personalInfo.Phone) && personalInfo.Phone.Length < 10) { validationResults.Add(new ValidationResult("Phone number must be at least 10 characters long")); isValid = false; } if (!isValid) { return string.Join("\n", validationResults.Select(r => r.ErrorMessage)); } return string.Empty; }
内容的提问来源于stack exchange,提问作者Qaisar Shabbir Awan
相关产品推荐
相关产品推荐

