Saturday, July 13, 2013

Custom Error Message in ASP.NET MVC


Consider a scenario where you want to customize your error message depending on the value entered by the user.

Model:

namespace Mvc4Test.Models
{
    public class Part
    {
        [AlternateValidation(Suggetion = "Please Use 123 (This is a Suggestion)")]
        public string PartNumber { get; set; }
    }

    public class AlternateValidation : ValidationAttribute
    {
        public string Suggetion { get; set; }
     
        protected override ValidationResult IsValid(object value,ValidationContext validationContext)
        {
            if (value != null)
            {
                if (value.ToString() == "123")
                {
                    return ValidationResult.Success;
                }
                else
                {
                   
                    return new ValidationResult(Suggetion);

                }
            }else
                return new ValidationResult("Value is Null");

        }
    }
}

View:

 @Html.EditorFor(model => model.PartNumber)
 @Html.ValidationMessageFor(model => model.PartNumber)


No comments:
Write comments
Recommended Posts × +