【发布时间】:2019-04-01 19:00:44
【问题描述】:
我正在尝试创建自己的客户端验证属性,该属性将在提交时验证表单的属性。我一直在参考以下 Microsoft 文档:https://docs.microsoft.com/en-us/aspnet/core/mvc/models/validation?view=aspnetcore-2.1#custom-validation。
我不确定如何将验证规则添加到 jQuery 的验证器对象。这是我已经走了多远:
我的ValidationAttribute如下
public class CannotEqualValue : ValidationAttribute, IClientModelValidator
{
private readonly string _value;
public CannotEqualValue(string value)
{
_value = value;
}
public void AddValidation(ClientModelValidationContext context)
{
if (context == null)
throw new ArgumentNullException(nameof(context));
MergeAttribute(context.Attributes, "data-val", "true");
MergeAttribute(
context.Attributes, "data-val-cannotbevalue", GetErrorMessage()); //???
MergeAttribute(
context.Attributes, "data-val-cannotbevalue-value", _value); //???
}
protected override ValidationResult IsValid(
object value,
ValidationContext validationContext)
{
var category = (Category) validationContext.ObjectInstance;
if (category.Name == _value)
return new ValidationResult(GetErrorMessage());
return ValidationResult.Success;
}
private bool MergeAttribute(
IDictionary<string, string> attributes,
string key,
string value)
{
if (attributes.ContainsKey(key)) return false;
attributes.Add(key, value);
return true;
}
private string GetErrorMessage()
{
return $"Name cannot be {_value}.";
}
}
ValidationAttribute 用在这样的模型中
public class Category
{
[Key]
public int Id { get; set; }
[Required(ErrorMessage = "Name is required and must not be empty.")]
[StringLength(200, ErrorMessage = "Name must not exceed 200 characters.")]
[CannotEqualValue("Red")]
public string Name { get; set; }
}
我在我的页面中同时引用了 jQuery 验证和不显眼。
我不确定如何将规则添加到 jQuery 的验证器对象:
$.validator.addMethod("cannotbevalue",
function(value, element, parameters) {
//???
});
$.validator.unobtrusive.adapters.add("cannotbevalue",
[],
function(options) {
//???
});
【问题讨论】:
标签: c# jquery asp.net validation asp.net-core-mvc