ASP.NET Core 3.1
这是我对该功能的实现,它可以在服务器端运行,并且可以与自定义错误消息一样灵活地进行jquery验证,就像其他任何属性一样:
属性:
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
public class MustBeIntegerAttribute : ValidationAttribute, IClientModelValidator
{
public void AddValidation(ClientModelValidationContext context)
{
MergeAttribute(context.Attributes, "data-val", "true");
var errorMsg = FormatErrorMessage(context.ModelMetadata.GetDisplayName());
MergeAttribute(context.Attributes, "data-val-mustbeinteger", errorMsg);
}
public override bool IsValid(object value)
{
return int.TryParse(value?.ToString() ?? "", out int newVal);
}
private bool MergeAttribute(
IDictionary<string, string> attributes,
string key,
string value)
{
if (attributes.ContainsKey(key))
{
return false;
}
attributes.Add(key, value);
return true;
}
}
客户端逻辑:
$.validator.addMethod("mustbeinteger",
function (value, element, parameters) {
return !isNaN(parseInt(value)) && isFinite(value);
});
$.validator.unobtrusive.adapters.add("mustbeinteger", [], function (options) {
options.rules.mustbeinteger = {};
options.messages["mustbeinteger"] = options.message;
});
最后是用法:
[MustBeInteger(ErrorMessage = "You must provide a valid number")]
public int SomeNumber { get; set; }