ASP.Net Core 3.1
我知道这是一个非常老的问题,但对于asp.net核心而言, IClientValidatable
不存在。我需要一种解决方案,可以与 jQuery Unobtrusive Validation
以及服务器验证结合使用,因此借鉴了这个 Stack Overflow 的问题链接, 我进行了一些小修改,使其适用于布尔字段,如复选框。
特性代码
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
public class MustBeTrueAttribute : ValidationAttribute, IClientModelValidator
{
public void AddValidation(ClientModelValidationContext context)
{
MergeAttribute(context.Attributes, "data-val", "true");
var errorMsg = FormatErrorMessage(context.ModelMetadata.GetDisplayName());
MergeAttribute(context.Attributes, "data-val-mustbetrue", errorMsg);
}
public override bool IsValid(object value)
{
return value != null && (bool)value == true;
}
private bool MergeAttribute(
IDictionary<string, string> attributes,
string key,
string value)
{
if (attributes.ContainsKey(key))
{
return false;
}
attributes.Add(key, value);
return true;
}
}
模型
[Display(Name = "Privacy policy")]
[MustBeTrue(ErrorMessage = "Please accept our privacy policy!")]
public bool PrivacyPolicy { get; set; }
客户端代码
$.validator.addMethod("mustbetrue",
function (value, element, parameters) {
return element.checked;
});
$.validator.unobtrusive.adapters.add("mustbetrue", [], function (options) {
options.rules.mustbetrue = {};
options.messages["mustbetrue"] = options.message;
});