none
Customize ValidationAttribute - error message with entity ID (or some unique identifier) RRS feed

  • Question

  • I haven't been able to find an answer to this (or I'm just new to DataAnnotations):

    class Customer : Entity
    {
       public string UniqueId { get; set; }
    
       [Required]
       public string LastName { get; set; }
    }
    

    When I do validation, I want the error message to say:

    LastName is a required field for Customer: {UniqueId}

    Currently the error message does not identify the entity in anyway. Thus looking at logs, there is no way to figure this out.

    BTW, I'm using validation on POCOs for a windows service/console application.

    Monday, June 6, 2016 7:37 PM

Answers

  • Hi kplkumar,

    >>"Currently the error message does not identify the entity in anyway."

    We could customize error message in required attribute. Code below is for your reference.

    [Required(ErrorMessage = "LastName is a required field for Customer")]
    public string LastName { get; set; }

    You also could define a validate arrtibute which inherited from RequiredAttribute to customize error message.

    [CustomRequiredAttribute]
    public string LastName { get; set; }
    public class CustomRequiredAttribute : System.ComponentModel.DataAnnotations.RequiredAttribute
    {
        private string displayName;
    
        private string entityName;
    
        public CustomRequiredAttribute()
        {
            this.ErrorMessage = "{0} is a required field for {1}";
        }
    
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            var attributes = validationContext.ObjectType.GetProperty(validationContext.MemberName).GetCustomAttributes(typeof(DisplayNameAttribute), true);
            if (attributes != null)
                this.displayName = (attributes[0] as DisplayNameAttribute).DisplayName;
            else
                this.displayName = validationContext.DisplayName;
    
            this.entityName = validationContext.ObjectType.Name;
    
            return base.IsValid(value, validationContext);
        }
    
        public override string FormatErrorMessage(string name)
        {
            return string.Format(this.ErrorMessageString, displayName, entityName);
        }
    }
    Best Regards,
    Li Wang

    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    Tuesday, June 7, 2016 5:43 AM
    Moderator