Data Conditional Annotation MVC4

2

I researched bales here and did not find a solution that I wanted. I would like to know if anyone has done anything similar in MVC4.

Model:

public class Trabalhador
{

    [Required(ErrorMessage = "*")]
    public int Id { get; set; }

    [Required(ErrorMessage = "*")]
    public String Nome { get; set; }

    public String Aposentado { get; set; }

    [Requerido caso o Aposentado seja "S"]
    public DateTime DataAposentadoria { get; set; }
}

View:

@Html.TextBoxFor(model => model.Id)
@Html.ValidationMessageFor(model => model.Id)

@Html.TextBoxFor(model => model.Nome)
@Html.ValidationMessageFor(model => model.Nome)

@Html.TextBoxFor(model => model.Aposentado)
@Html.ValidationMessageFor(model => model.Aposentado)

@Html.TextBoxFor(model => model.DataAposentadoria)
@Html.ValidationMessageFor(model => model.DataAposentadoria)

Here is the X of Questao, I in my form wish all fields, however I want you to force me to enter the Retirement Date only in the case of a specific value in the Retired attribute (which in this case would be "S" or any other value I want). I looked at several posts even here on the Stack, but none of the templates worked.

link link link link

    
asked by anonymous 07.05.2014 / 15:57

4 answers

1

My solution:

[AttributeUsageAttribute(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)]
public class DataAposentadoria : ValidationAttribute
{
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var property = validationContext.ObjectInstance.GetType().GetProperty("Aposentado");

        if (property == null)
            return new ValidationResult("Propriedade desconhecida: 'Aposentado'");

        var propertyValue = property.GetValue(validationContext.ObjectInstance, null);

        if (propertyValue != null && propertyValue.ToString() == "S" && value == null)
        {
            return new ValidationResult("Data de aposentadoria deve ser preenchida!");
        }
        return ValidationResult.Success;
    }
}

To use:

public String Aposentado { get; set; }

[DataAposentadoria]
public DateTime? DataAposentadoria { get; set; }

Explaining, when it enters the property, it will try to find out if there is a "Retired" property, if it exists it takes the value and validates it.

Of course you can increment to put a dynamic property.

    
07.05.2014 / 16:13
0

You can implement an attribute that does a custom validation in the same way as Required , but only when the condition is satisfied, and use this attribute instead of Required .

In this attribute implement the IClientValidatable interface to be able to validate the client, when using non-obstructive validation, and implement a validation implementation with javascript.

An example is in this SOEN response:

I have adapted the response attribute presented above to have non-obstructive validation on the client:

public class RequiredIfAttribute : RequiredAttribute, IClientValidatable
{
    private String PropertyName { get; set; }
    private Object Comparand { get; set; }

    public RequiredIfAttribute(String propertyName, Object comparand)
    {
        PropertyName = propertyName;
        Comparand = comparand;
    }

    protected override ValidationResult IsValid(object value, ValidationContext context)
    {
        var instance = context.ObjectInstance;
        var type = instance.GetType();
        var proprtyvalue = type.GetProperty(PropertyName).GetValue(instance, null);

        if (proprtyvalue.ToString() == Comparand.ToString())
        {
            var result = base.IsValid(value, context);
            return result;
        }

        return ValidationResult.Success;
    }

    IEnumerable<ModelClientValidationRule> IClientValidatable.GetClientValidationRules(
        ModelMetadata metadata,
        ControllerContext context)
    {
        var requiredIfRule = new ModelClientValidationRule();
        requiredIfRule.ErrorMessage = this.ErrorMessageString;
        requiredIfRule.ValidationType = "requiredif";
        requiredIfRule.ValidationParameters.Add("propertyname", this.PropertyName);
        requiredIfRule.ValidationParameters.Add("comparand", this.Comparand);
        yield return requiredIfRule;
    }
}

Create a javascript file, and include it in the page with the field to be validated:

$.validator.addMethod("requiredif", function (value, element, params) {
    return $(params.propertyname).val() == params.comparand
        ? value != null && value != "" && value != undefined
        : true;
});

$.validator.unobtrusive.adapters.add(
    "requiredif",
    ["propertyname", "comparand"],
    function (options) {
        options.rules["propertyname"] = "#" + options.params.propertyname;
        options.rules["comparand"] = options.params.comparand;
        options.messages["requiredif"] = options.message;
    });

And use it like this:

public class Trabalhador
{
    [Required(ErrorMessage = "*")]
    public int Id { get; set; }

    [Required(ErrorMessage = "*")]
    public String Nome { get; set; }

    public String Aposentado { get; set; }

    [RequiredIf("Aposentado", "S")]
    public DateTime DataAposentadoria { get; set; }
}

Reference:

I could not determine the authorship of the RequiredIf attribute ... searching Google for RequiredIfAttribute RequiredAttribute returns numerous sources where this code is used. I'll search more, and if you find, I'll reference here. If someone finds the author, please feel free to edit the answer, or make a comment.

    
07.05.2014 / 16:07
0

Create a class that will be the Attribute, with inheritance in the abstract class ValidationAttribute is validating the server, and implements the

07.05.2014 / 19:12
0

Gentlemen, the FCCDias solution worked, but I had to make a small change, I did not want to change its code, because I could not understand that block of JavaScript, but the only change I made was in the last line: Did not work: return $ (params.item) .val () == params.value & value! = '' & value.length == 10; It worked: Return "";

Thank you all for the help;

    
08.05.2014 / 20:16