1

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};

[RangeIf("retired",20,50)]
public int retirementAge {get, set};

How can I do that?

1 Answer 1

1

You need to create your custom validation attribute like this:

public class RangeIfAttribute : ValidationAttribute
{
    protected RangeAttribute _innerAttribute;

    public string DependentProperty { get; set; }

    public RangeIfAttribute(string dependentProperty, int minimum, int maximum)
    {
        _innerAttribute = new RangeAttribute(minimum, maximum);
        DependentProperty = dependentProperty;
    }

    public RangeIfAttribute(string dependentProperty, double minimum, double maximum)
    {
        _innerAttribute = new RangeAttribute(minimum, maximum);
        DependentProperty = dependentProperty;
    }

    public RangeIfAttribute(string dependentProperty, Type type, string minimum, string maximum)
    {
        _innerAttribute = new RangeAttribute(type, minimum, maximum);
        DependentProperty = dependentProperty;
    }

    public override string FormatErrorMessage(string name)
    {
        return _innerAttribute.FormatErrorMessage(name);
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        // get a reference to the property this validation depends upon
        var containerType = validationContext.ObjectInstance.GetType();
        var field = containerType.GetProperty(DependentProperty);

        if (field != null && field.PropertyType.Equals(typeof(bool)))
        {
            // get the value of the dependent property                
            var dependentValue = (bool)(field.GetValue(validationContext.ObjectInstance, null));

            // if dependentValue is true...
            if (dependentValue)
            {
                if (!_innerAttribute.IsValid(value))
                    // validation failed - return an error
                    return new ValidationResult(FormatErrorMessage(validationContext.DisplayName), new[] { validationContext.MemberName });
            }
        }

        return ValidationResult.Success;
    }
}

Then, you can use it in your Model just like in your question.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.