attribute dependent on another field

43,836

Solution 1

Take a look at this: http://blogs.msdn.com/b/simonince/archive/2010/06/04/conditional-validation-in-mvc.aspx

I've modded the code somewhat to suit my needs. Perhaps you benefit from those changes as well.

public class RequiredIfAttribute : ValidationAttribute
{
    private RequiredAttribute innerAttribute = new RequiredAttribute();
    public string DependentUpon { get; set; }
    public object Value { get; set; }

    public RequiredIfAttribute(string dependentUpon, object value)
    {
        this.DependentUpon = dependentUpon;
        this.Value = value;
    }

    public RequiredIfAttribute(string dependentUpon)
    {
        this.DependentUpon = dependentUpon;
        this.Value = null;
    }

    public override bool IsValid(object value)
    {
        return innerAttribute.IsValid(value);
    }
}

public class RequiredIfValidator : DataAnnotationsModelValidator<RequiredIfAttribute>
{
    public RequiredIfValidator(ModelMetadata metadata, ControllerContext context, RequiredIfAttribute attribute)
        : base(metadata, context, attribute)
    { }

    public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()
    {
        // no client validation - I might well blog about this soon!
        return base.GetClientValidationRules();
    }

    public override IEnumerable<ModelValidationResult> Validate(object container)
    {
        // get a reference to the property this validation depends upon
        var field = Metadata.ContainerType.GetProperty(Attribute.DependentUpon);

        if (field != null)
        {
            // get the value of the dependent property
            var value = field.GetValue(container, null);

            // compare the value against the target value
            if ((value != null && Attribute.Value == null) || (value != null && value.Equals(Attribute.Value)))
            {
                // match => means we should try validating this field
                if (!Attribute.IsValid(Metadata.Model))
                    // validation failed - return an error
                    yield return new ModelValidationResult { Message = ErrorMessage };
            }
        }
    }
}

Then use it:

public DateTime? DeptDateTime { get; set; }
[RequiredIf("DeptDateTime")]
public string DeptAirline { get; set; }

Solution 2

Just use the Foolproof validation library that is available on Codeplex: https://foolproof.codeplex.com/

It supports, amongst others, the following "requiredif" validation attributes / decorations:

[RequiredIf]
[RequiredIfNot]
[RequiredIfTrue]
[RequiredIfFalse]
[RequiredIfEmpty]
[RequiredIfNotEmpty]
[RequiredIfRegExMatch]
[RequiredIfNotRegExMatch]

To get started is easy:

  1. Download the package from the provided link
  2. Add a reference to the included .dll file
  3. Import the included javascript files
  4. Ensure that your views references the included javascript files from within its HTML for unobtrusive javascript and jquery validation.

Solution 3

Using NuGet Package Manager I intstalled this: https://github.com/jwaliszko/ExpressiveAnnotations

And this is my Model:

using ExpressiveAnnotations.Attributes;

public bool HasReferenceToNotIncludedFile { get; set; }

[RequiredIf("HasReferenceToNotIncludedFile == true", ErrorMessage = "RelevantAuditOpinionNumbers are required.")]
public string RelevantAuditOpinionNumbers { get; set; }

I guarantee you this will work!

Solution 4

I have not seen anything out of the box that would allow you to do this.

I've created a class for you to use, it's a bit rough and definitely not flexible.. but I think it may solve your current problem. Or at least put you on the right track.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.Globalization;

namespace System.ComponentModel.DataAnnotations
{
    [AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)]
    public sealed class RequiredIfAttribute : ValidationAttribute
    {
        private const string _defaultErrorMessage = "'{0}' is required";
        private readonly object _typeId = new object();

        private string  _requiredProperty;
        private string  _targetProperty;
        private bool    _targetPropertyCondition;

        public RequiredIfAttribute(string requiredProperty, string targetProperty, bool targetPropertyCondition)
            : base(_defaultErrorMessage)
        {
            this._requiredProperty          = requiredProperty;
            this._targetProperty            = targetProperty;
            this._targetPropertyCondition   = targetPropertyCondition;
        }

        public override object TypeId
        {
            get
            {
                return _typeId;
            }
        }

        public override string FormatErrorMessage(string name)
        {
            return String.Format(CultureInfo.CurrentUICulture, ErrorMessageString, _requiredProperty, _targetProperty, _targetPropertyCondition);
        }

        public override bool IsValid(object value)
        {
            bool result             = false;
            bool propertyRequired   = false; // Flag to check if the required property is required.

            PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(value);
            string requiredPropertyValue            = (string) properties.Find(_requiredProperty, true).GetValue(value);
            bool targetPropertyValue                = (bool) properties.Find(_targetProperty, true).GetValue(value);

            if (targetPropertyValue == _targetPropertyCondition)
            {
                propertyRequired = true;
            }

            if (propertyRequired)
            {
                //check the required property value is not null
                if (requiredPropertyValue != null)
                {
                    result = true;
                }
            }
            else
            {
                //property is not required
                result = true;
            }

            return result;
        }
    }
}

Above your Model class, you should just need to add:

[RequiredIf("retirementAge", "retired", true)]
public class MyModel

In your View

<%= Html.ValidationSummary() %> 

Should show the error message whenever the retired property is true and the required property is empty.

Hope this helps.

Share:
43,836

Related videos on Youtube

Ahmet Dalyan
Author by

Ahmet Dalyan

Updated on July 09, 2022

Comments

  • Ahmet Dalyan
    Ahmet Dalyan almost 2 years

    In a model of my ASP.NET MVC application I would like validate a textbox as required only if a specific checkbox is checked.

    Something like

    public bool retired {get, set};
    
    [RequiredIf("retired",true)]
    public string retirementAge {get, set};
    

    How can I do that?

    Thank you.

    • jwaliszko
      jwaliszko almost 10 years
      [RequiredIf("retired == true")], more here
  • tkerwood
    tkerwood about 12 years
    you need to add ' DataAnnotationsModelValidatorProvider.RegisterAdapter( typeof(RequiredIfAttribute), typeof(RequiredIfValidator));' to your global.asax.cs to get this to work. (as described in the link RickardN provided.
  • Ian Kemp
    Ian Kemp over 10 years
    Would be nice if you could provide a complete project in your repo, that includes all the required references like System.Linq.Dynamic. Furthermore you seem to be using a custom version of System.Linq.Dynamic as the Microsoft one has an ExpressionParser.Parse() method that takes 1 argument, but you are calling a 2-argument version.
  • karaxuna
    karaxuna over 10 years
    Thanks @IanKemp, I'll consider your suggestions and improve repository
  • Admin
    Admin about 10 years
    Link? It seems to be working fine for me - I'm using EF 6. I downloaded the sourcecode for Foolproof and compiled it myself so perhaps that explains why it is working for me?
  • David Poxon
    David Poxon about 10 years
  • Shivani
    Shivani about 8 years
    Can I use: [RequiredIfTrue] [RequiredIfFalse] - on single property with 2 different dependent properties?Example: [RequiredIfFalse("IsQuote", ErrorMessage = @"Provider must be entered.")] [RequiredIfTrue("IsIfa", ErrorMessage = @"Provider must be entered.")] [XmlElement("Provider", IsNullable = true)] public string Provider { get; set; }
  • Admin
    Admin about 8 years
    Most probably. My recommendation is to make the change and then run a unit test against it to see whether it works as intended.
  • 3 rules
    3 rules over 7 years
    @karaxuna What do I do with ExpressionParser there is an error showing me on that?
  • Hanady
    Hanady over 6 years
    ModelMetadata.FromLambdaExpression(ex, html.ViewData).IsRequired is always returning false even thought the dependent upon property is true/false
  • Cory-G
    Cory-G almost 6 years
    The if after // compare the value against the target value should instead read (value == null && Attribute.Value == null) as the first part of the condition. (change != to ==)