在以前版本的MVC框架中,自定义验证将通过实现IClientValidatable
和GetClientValidationRules
方法来实现.
然而在ASP.Net核心MVCwe do not have this interface,尽管我们有IClientModelValidator
,它定义了一个非常相似的方法.然而,它的实现从未被调用.
那么,我们如何在ASP中实现自定义属性的客户端验证呢.网络核心MVC?
在以前版本的MVC框架中,自定义验证将通过实现IClientValidatable
和GetClientValidationRules
方法来实现.
然而在ASP.Net核心MVCwe do not have this interface,尽管我们有IClientModelValidator
,它定义了一个非常相似的方法.然而,它的实现从未被调用.
那么,我们如何在ASP中实现自定义属性的客户端验证呢.网络核心MVC?
IClient型号Validator
实际上是正确的接口.我在下面做了一个精心设计的示例实现.
Note:
RC1和RC2之间的IClient型号Validator
接口有一个breaking change.这两个选项如下所示-代码的睡觉在两个版本之间是相同的.
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
public sealed class CannotBeRedAttribute : ValidationAttribute, IClient型号Validator
{
public override bool IsValid(object value)
{
var message = value as string;
return message?.ToUpper() == "RED";
}
public void AddValidation(Client型号ValidationContext context)
{
MergeAttribute(context.Attributes, "data-val", "true");
var errorMessage = FormatErrorMessage(context.型号Metadata.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, IClient型号Validator
{
public override bool IsValid(object value)
{
var message = value as string;
return message?.ToUpper() == "RED";
}
public IEnumerable<型号ClientValidationRule> GetClientValidationRules(
Client型号ValidationContext context)
{
yield return new 型号ClientValidationRule(
"cannotbered",
FormatErrorMessage(ErrorMessage));
}
}
public class Contact型号
{
[CannotBeRed(ErrorMessage = "Red is not allowed!")]
public string Message { get; set; }
}
@model WebApplication22.型号s.Contact型号
<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>
}