ASP.Net Core 3.1
我知道这是一个非常古老的问题,但对于 asp.net 核心,IClientValidatable 不存在,我想要一个适用于jQuery Unobtrusive Validation 以及服务器验证的解决方案,所以借助这个 SO 问题@ 987654321@ 我做了一个小修改,适用于复选框等布尔字段。
属性代码
[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;
});