ASP.Net Core MVC – 自定义属性的客户端validation

在以前版本的MVC框架中,将通过实现IClientValidatableGetClientValidationRules方法来实现自定义validation。

但是在ASP.Net Core MVC中我们没有这个接口 ,尽管我们确实有IClientModelValidator ,它定义了一个非常相似的方法。 然而,其实现永远不会被调用。

那么 – 我们如何在ASP.NET Core MVC中为自定义属性实现客户端validation?

IClientModelValidator实际上是正确的接口。 我在下面做了一个人为的示例实现。

注意: RC1和RC2之间的IClientModelValidator接口发生了重大变化 。 两个选项如下所示 – 其余代码在两个版本之间是相同的。

属性(RC2及以上)

 [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)] public sealed class CannotBeRedAttribute : ValidationAttribute, IClientModelValidator { public override bool IsValid(object value) { var message = value as string; return message?.ToUpper() == "RED"; } public void AddValidation(ClientModelValidationContext context) { MergeAttribute(context.Attributes, "data-val", "true"); var errorMessage = FormatErrorMessage(context.ModelMetadata.GetDisplayName()); MergeAttribute(context.Attributes, "data-val-cannotbered", errorMessage); } private bool MergeAttribute( IDictionary attributes, string key, string value) { if (attributes.ContainsKey(key)) { return false; } attributes.Add(key, value); return true; } } 

属性(RC1)

 [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)] public sealed class CannotBeRedAttribute : ValidationAttribute, IClientModelValidator { public override bool IsValid(object value) { var message = value as string; return message?.ToUpper() == "RED"; } public IEnumerable GetClientValidationRules( ClientModelValidationContext context) { yield return new ModelClientValidationRule( "cannotbered", FormatErrorMessage(ErrorMessage)); } } 

模型

 public class ContactModel { [CannotBeRed(ErrorMessage = "Red is not allowed!")] public string Message { get; set; } } 

视图

 @model WebApplication22.Models.ContactModel 
@section scripts { }