attribute dependent on another field

后端 未结 5 1466
抹茶落季
抹茶落季 2020-11-27 04:03

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 bo         


        
相关标签:
5条回答
  • 2020-11-27 04:36

    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.

    0 讨论(0)
  • 2020-11-27 04:47

    Try my custom validation attribute:

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

    It supports multiple conditions.

    0 讨论(0)
  • 2020-11-27 04:49

    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.
    0 讨论(0)
  • 2020-11-27 04:52

    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!

    0 讨论(0)
  • 2020-11-27 05:02

    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; }
    
    0 讨论(0)
提交回复
热议问题