在以前版本的MVC框架中,可以通过实施IClientValidatable
和GetClientValidationRules
方法来实现自定义验证。
然而,在ASP.Net Core MVC we do not have this interface中,尽管我们确实有IClientModelValidator
,它定义了一个非常相似的方法。然而,其实现永远不会被调用。
那么 - 我们如何在ASP.NET Core MVC中为自定义属性实现客户端验证?
答案 0 :(得分:39)
IClientModelValidator
实际上是正确的界面。我在下面做了一个人为的示例实现。
注意:强>
RC1和RC2之间的IClientModelValidator
接口有一个breaking change。这两个选项如下所示 - 其余代码在两个版本之间都是相同的。
[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<string, string> attributes,
string key,
string value)
{
if (attributes.ContainsKey(key))
{
return false;
}
attributes.Add(key, value);
return true;
}
}
[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<ModelClientValidationRule> 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
<form asp-action="Contact" method="post">
<label asp-for="Message"></label>
<input asp-for="Message" />
<span asp-validation-for="Message"></span>
<input type="submit" value="Save" />
</form>
@section scripts {
<script src="~/lib/jquery-validation/dist/jquery.validate.min.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js"></script>
<script>
$.validator.addMethod("cannotbered",
function (value, element, parameters) {
return value.toUpperCase() !== "RED";
});
$.validator.unobtrusive.adapters.add("cannotbered", [], function (options) {
options.rules.cannotbered = {};
options.messages["cannotbered"] = options.message;
});
</script>
}