如何为所有必需的属性验证设置相同的错误消息?

时间:2019-06-12 11:57:40

标签: asp.net-core

我是.net core的新手。 对于ASP.NET框架,以下代码将所有必需的验证消息更改为“此字段为必需”。

 public class CustomRequiredAttribute:RequiredAttribute, IClientValidatable
    {

        public override bool IsValid(object value)
        {
            return base.IsValid(value);
        }

        public override string FormatErrorMessage(string name)
        {
            return base.FormatErrorMessage(name); // expandable to format given message later
        }

        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            return new[] { new ModelClientValidationRule { ErrorMessage = "This field is required", ValidationType = "required" } };
        }
    }

您如何对.net core做同样的事情?

 public class CustomRequiredAttribute:RequiredAttribute
    { 
      //set required field message to : This field is requried.
    }

1 个答案:

答案 0 :(得分:1)

根据您的要求,您可以像

那样实现RequiredAttribute, IClientModelValidator
public class DefaultRequiredAttribute: RequiredAttribute, IClientModelValidator
{
    public DefaultRequiredAttribute()
    {
        ErrorMessage = "This field is required";
    }

    public void AddValidation(ClientModelValidationContext context)
    {
        MergeAttribute(context.Attributes, "data-val", "true");
        MergeAttribute(context.Attributes, "data-val-required", ErrorMessage);
    }
    private bool MergeAttribute(IDictionary<string, string> attributes, string key, string value)
    {
        if (attributes.ContainsKey(key))
        {
            return false;
        }

        attributes.Add(key, value);
        return true;
    }
}

并使用

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    [DefaultRequired]
    public string UserImage { get; set; }
}