I'm trying to implement a validator based on another field.
My domain class.
[Required]
public string _tipoDeControle { get; set; }
[NotMapped]
public TipoDeControle TipoDeControle
{
get { return ExtensaoDeEnumerador.ObterEnumeradorPorNome<TipoDeControle>(_tipoDeControle?.Trim()); }
set { _tipoDeControle = value.ToString(); }
}
[RequiredEqual("TipoDeControle", "Transacao")]
public decimal? Valor { get; set; }
My Enum.
public enum TipoDeControle
{
[Description("Transação")]
Transacao,
[Description("Horário")]
Horario,
[Description("Data")]
Data,
[Description("Dias")]
Dias
}
I tried to do it as follows;
using System;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
namespace Infraestrutura.Utilitario
{
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public sealed class RequiredEqualAttribute : ValidationAttribute
{
public string EnumProperty { get; set; }
public string EnumValue { get; private set; }
public override bool RequiresValidationContext { get { return true; } }
/// <summary>
/// Faz a validação para um tipo Enum.
/// </summary>
/// <param name="_enum"></param>
/// <param name="enumValue"></param>
public RequiredEqualAttribute(string objeto, string enumValue)
: base("'{0}' é requerido porque '{1}' foi preenchido {2}.")
{
this.EnumProperty = objeto;
this.EnumValue = enumValue;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (validationContext == null)
{
throw new ArgumentNullException("validationContext");
}
if (this.EnumProperty != null)
return ValidationEnum(value, validationContext);
return ValidationResult.Success;
}
private ValidationResult ValidationEnum(object value, ValidationContext validationContext)
{
string enumValue = meuenum.ObterDescricao();
if (object.Equals(enumValue, this.EnumValue))
{
if (value == null)
{
return new ValidationResult(this.FormatErrorMessage(validationContext.DisplayName));
}
string val = value as string;
if (val != null && val.Trim().Length == 0)
{
return new ValidationResult(this.FormatErrorMessage(validationContext.DisplayName));
}
}
return ValidationResult.Success;
}
public override string FormatErrorMessage(string name)
{
return string.Format(
CultureInfo.CurrentCulture,
base.ErrorMessageString,
name,
this.EnumProperty.GetType().Name,
this.EnumValue);
}
}
}
What I want to do is that when Enum has the value equal to Transaction my field Valor
is required.
But I could not do the validation correctly. How could this type of validation be what I missed?