ASP.NET Core 2.0自定义验证特性客户端验证失效问题求助
嘿,这个问题我之前也碰到过!核心原因是:虽然你的EmbeddedCodeAttribute继承自RegularExpressionAttribute,但ASP.NET Core的非侵入式客户端验证不会自动“识别”这个自定义特性——框架需要明确的指令,知道如何把你的自定义验证规则转换成客户端能理解的data-val-*属性。
下面是具体的解决步骤:
解决方案:让自定义特性支持客户端验证
1. 修改自定义特性,实现IClientModelValidator接口
更新你的EmbeddedCodeAttribute,添加客户端验证逻辑,让框架知道如何生成客户端验证所需的HTML属性:
using System; using System.ComponentModel.DataAnnotations; using Microsoft.AspNetCore.Mvc.ModelBinding.Validation; public class EmbeddedCodeAttribute : RegularExpressionAttribute, IClientModelValidator { // 替换成你实际使用的正则表达式 private const string EmbeddedCodePattern = @"你的正则表达式内容"; public EmbeddedCodeAttribute() : base(EmbeddedCodePattern) { // 可以自定义错误提示消息 ErrorMessage = "请输入有效的嵌入式代码格式"; } public void AddValidation(ClientModelValidationContext context) { if (context == null) throw new ArgumentNullException(nameof(context)); // 向输入元素添加客户端验证所需的data属性 MergeAttribute(context.Attributes, "data-val", "true"); MergeAttribute(context.Attributes, "data-val-regex", ErrorMessage); MergeAttribute(context.Attributes, "data-val-regex-pattern", EmbeddedCodePattern); } // 辅助方法:避免重复添加相同的HTML属性 private void MergeAttribute(IDictionary<string, string> attributes, string key, string value) { if (!attributes.ContainsKey(key)) attributes.Add(key, value); } }
2. 确认项目中的验证配置
确保你的Startup.cs里已经启用了非侵入式验证和客户端验证(ASP.NET Core 2.0默认是启用的,但可以明确检查):
public void ConfigureServices(IServiceCollection services) { services.AddMvc() .AddMvcOptions(options => { options.ClientValidationEnabled = true; options.UnobtrusiveJavaScriptEnabled = true; }); }
3. 验证HTML输出是否正确
渲染表单后,检查对应的EmbeddedCode输入元素,应该能看到以下属性:
<input type="text" name="EmbeddedCode" data-val="true" data-val-regex="请输入有效的嵌入式代码格式" data-val-regex-pattern="你的正则表达式内容" />
只要这些属性存在,jquery.validate.unobtrusive就能自动识别并执行客户端验证了。
补充说明
直接使用[RegularExpression]时,ASP.NET Core框架内置了对应的客户端验证适配器(RegularExpressionAttributeAdapter),会自动生成上述data-val-*属性。而自定义特性继承后,框架不会自动关联这个适配器,所以需要我们手动实现IClientModelValidator来提供客户端规则。
内容的提问来源于stack exchange,提问作者GrayFox
相关产品推荐
相关产品推荐

