m.e*_*son 25 c# asp.net validation asp.net-core-mvc asp.net-core
在以前版本的MVC框架中,将通过实现IClientValidatable和GetClientValidationRules方法来实现自定义验证.
但是在ASP.Net Core MVC中我们没有这个接口,尽管我们确实有IClientModelValidator一个定义非常相似的方法.然而,其实现永远不会被调用.
那么 - 我们如何在ASP.NET Core MVC中为自定义属性实现客户端验证?
Wil*_*Ray 45
该IClientModelValidator实际上是在正确的接口.我在下面做了一个人为的示例实现.
注意: RC1和RC2之间的接口发生
了重大变化IClientModelValidator.两个选项如下所示 - 两个版本之间的其余代码相同.
[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;
}
}
Run Code Online (Sandbox Code Playgroud)
[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));
}
}
Run Code Online (Sandbox Code Playgroud)
public class ContactModel
{
[CannotBeRed(ErrorMessage = "Red is not allowed!")]
public string Message { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
@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>
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
18796 次 |
| 最近记录: |