Attribute
public class ValidationIfAposentado : ValidationAttribute, IClientValidatable
{
public String CompareProperty {get;set;}
public string CompareValue { get; set; }
public ValidationIfAposentado(String CompareProperty, String CompareValue)
{
this.CompareProperty = CompareProperty;
this.CompareValue = CompareValue;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
PropertyInfo propertyInfo = validationContext.ObjectInstance.GetType().GetProperty(CompareProperty);
if (propertyInfo != null)
{
object valor = propertyInfo.GetValue(validationContext.ObjectInstance, null);
if (!(valor != null && CompareValue.Equals(valor.ToString())))
{
return new ValidationResult(this.ErrorMessage);
}
}
return ValidationResult.Success;
}
IEnumerable<ModelClientValidationRule> IClientValidatable.GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var erro = new ModelClientValidationRequiredRule(this.ErrorMessage);
erro.ValidationType = "validationifaposentado";
erro.ValidationParameters.Add("item", CompareProperty);
erro.ValidationParameters.Add("value", CompareValue);
yield return erro;
}
}
Classe
public class Trabalhador
{
[Required(ErrorMessage = "*")]
public int Id { get; set; }
[Required(ErrorMessage = "*")]
public String Nome { get; set; }
[MinLength(1), MaxLength(1)]
public String Aposentado { get; set; }
[ValidationIfAposentado("Aposentado", "S", ErrorMessage="Como é aposentado digite a data de aposentadoria")]
[DataType(DataType.Date)]
public DateTime? DataAposentadoria { get; set; }
}
Javascript:
<script src="/Scripts/jquery-2.1.0.js"></script>
<script src="/Scripts/jquery.validate.js"></script>
<script src="/Scripts/jquery.validate.unobtrusive.js"></script>
<script>
jQuery.validator.unobtrusive.adapters.add("validationifaposentado", ["item", "value"],
function (options) {
options.rules['validationifaposentado'] = {
item: "#" + options.params.item,
value: options.params.value,
}
options.messages["validationifaposentado"] = options.message;
});
jQuery.validator.addMethod("validationifaposentado", function (value, element, params) {
if ($(params.item).val() === undefined || $(params.item).val() == '') {
return true;
}
return $(params.item).val() == params.value && value != '' && value.length == 10;
});
</script>