Search code examples
c#asp.net-coreasp.net-web-apidata-annotationsvalidationattribute

Override ValidationAttribute ErrorMessage, from string to new ErrorModel Class


I'm currently learning Net core, can anybody share with me how to override dataAnnotation ErrorMessage from string to object.

instead of ErrorMessage as string

[RegularExpression(@"^[a-zA-Z0-9._-]{3,15}$", ErrorMessage = "Please make sure username is between 3 to 15 character and may also contain '._-' special character only.")]
public string Username { get; set; }

to ErrorMessage as object

[RegularExpression(@"^[a-zA-Z0-9._-]{3,15}$", ErrorMessage = new ErrorModel { MESSAGE = "Something went wrong when updating username.Please contact system admin if issue persist.", STATUS_CODE = "1"})]
public string Username { get; set; }

I have created an ErrorModel class

public class ErrorModel
{
    public string STATUS_CODE { get; set; }
    public string MESSAGE { get; set; }
}

I want to override ErrorMessage from string to object for all attribute derived from ValidationAttribute, is this doable?

Regards, Hazmin


Solution

  • RegularExpressionAttribute inherits from ValidationAttribute,the ErrorMessage is not declared with abstract or virtual so that it could not be extended or modified.

    From your scenario,you want to display error message with both message and status code,you could custom response like below:

    Model:

    public class ErrorModel
    {
        public string Key { get; set; }
        public string STATUS_CODE { get; set; }
        public string MESSAGE { get; set; }
    }
    public class Test
    {
    
        [RegularExpression(@"^[a-zA-Z0-9._-]{3,15}$")]
        public string Username { get; set; } 
        //other properties
    }
    

    Controller:

    [HttpPost]
    public async Task<IActionResult> Create(Test model)
    {
        if (ModelState.IsValid)
        {               
           //...
        }
        var errorList = new List<ErrorModel>();
        //1.foreach the key
        foreach (var modelStateKey in ModelState.Keys)
        {
            var modelStateVal = ModelState[modelStateKey];
            //2.check if this key contains error
            foreach (var error in modelStateVal.Errors)
            {
                var key = modelStateKey;
                if (key == "Username")
                {
                    errorList.Add(new ErrorModel { Key = key, MESSAGE = "Something went wrong when updating username.Please contact system admin if issue persist.", STATUS_CODE = "1" });                       
                }
                else {
                    errorList.Add(new ErrorModel { Key = key, MESSAGE = error.ErrorMessage, STATUS_CODE = "1" });
                }
            }                
        }
        return BadRequest(errorList);
    }