我正在尝试创建自己的客户端验证属性,该属性将在提交时验证表单的属性。我一直在参考以下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) {
//???
});
答案 0 :(得分:1)
您在MergeAttribute(..)
方法中的AddValidation()
行代码是正确的,并将添加data-val-*
属性以进行客户端验证。
您的脚本必须是
$.validator.addMethod("cannotbevalue", function(value, element, params) {
if ($(element).val() == params.targetvalue) {
return false;
}
return true;
});
$.validator.unobtrusive.adapters.add('cannotbevalue', ['value'], function(options) {
options.rules['cannotbevalue'] = { targetvalue: options.params.value };
options.messages['cannotbevalue'] = options.message;
});