3

I have the following custom ValidationAttribute that works the same way as the Required validation attribute, but I accept the name of a property that will have its value concatenated to the error message. However, the error message always comes as "The [fieldName] field is required".

What is wrong with it?

public class RequiredFieldWithValueOnErrorMessage : ValidationAttribute
    {
// a little portuguese lesson :P
// propriedade = property
// mensagemDeErro = errorMessage

        public RequiredFieldWithValueOnErrorMessage (String propriedade, String mensagemDeErro)
        {
            if (!String.IsNullOrEmpty(mensagemDeErro))
            {
                this.ErrorMessage = mensagemDeErro;
            }
            else
            {
                this.ErrorMessageResourceName = "MensagemCampoRequerido";
                this.ErrorMessageResourceType = typeof(MensagensInterfaceUsuario);
            }

            Propriedade = propriedade;
        }

        private String Propriedade { get; set; }

        public override string FormatErrorMessage(string name)
        {
            return String.Format(ErrorMessage, name);
        }

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            Object instance = validationContext.ObjectInstance;
            Type type = instance.GetType();
            Object propertyValue = type.GetProperty(Propriedade).GetValue(instance, null);
            if (value == null || value.ToString() == "0" || String.IsNullOrWhiteSpace(value.ToString()))
            {
                return new ValidationResult(FormatErrorMessage(propertyValue.ToString()));
            }
            return ValidationResult.Success;
        }
    }
juliano.net
  • 7,982
  • 13
  • 70
  • 164
  • One thing that I've found is that if I change the type of the property being validated to Int64? (nullable int), it works. Why? – juliano.net May 16 '14 at 19:19

0 Answers0