3

Given a simplified class, like below:

public class Cliente
{
    [Display(Name = "Usuário")]
    [Required(ErrorMessage = "Informe um nome de usuário")]
    [EmailAddress(ErrorMessage = "Informe um e-mail válido")]
    [Remote("verificarUsernameCadastrado", "Validate", HttpMethod = "POST")]
    public String Username { get; set; }
}

I'm relatively new on the MVC world and I was thinking.. Is there a way to get, in the controller, the custom error message used with data annotation?

For instance, if I access the property Username in an action, I'd like to get the error message that I gave for EmailAddress (in this case, "Informe um e-mail válido").

I can easily duplicate this message where I want to use, but I'd really like to know if it's possible to do that.

Thanks in advance!

2 Answers 2

4

You can do this using reflection, better used as an extension method:

public static T GetAttribute<T>(this object instance, string propertyName) where T : Attribute
{
    var attrType = typeof(T);
    var property = instance.GetType().GetProperty(propertyName);
    return (T)property .GetCustomAttributes(attrType, false).First();
}

Usage:

var errorMessage = client.GetAttribute<EmailAddressAttribute>("Username").ErrorMessage;
Sign up to request clarification or add additional context in comments.

1 Comment

That is exactly what I was looking for. That's why Stack Overflow is so great. Thanks a lot!
2

You can get this from the ModelState when you POST to the controller method:

public ActionResult MyMethod(model MyModel)
{
    if (ModelState.IsValid)
    {
         // normal processing
    }
    else
    {
        if (ModelState["Username"].Errors.Count > 0)
        {
            var msg = ModelState["Username"].Errors[0].ErrorMessage;
        }
    }
}

1 Comment

Yeah, I've used this already. But in the current case, my model is null, so the ModelState doesn't have any errors. That's why I wanna directly get the custom error message that I gave. In any case, I upvoted your answer as I consider it useful. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.