C# ValidationAttribute required when

 public class RequiredIfAttribute : ValidationAttribute, IClientValidatable
    {
        private String PropertyName { get; set; }
        private Object DesiredValue { get; set; }
        private readonly RequiredAttribute _innerAttribute;

        public RequiredIfAttribute(String propertyName, Object desiredvalue)
        {
            PropertyName = propertyName;
            DesiredValue = desiredvalue;
            _innerAttribute = new RequiredAttribute();
        }

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

            if (dependentValue.ToString() == DesiredValue.ToString())
            {
                if (!_innerAttribute.IsValid(value))
                {
                    return new ValidationResult(FormatErrorMessage(context.DisplayName), new[] { context.MemberName });
                }
            }
            return ValidationResult.Success;
        }

        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            var rule = new ModelClientValidationRule
            {
                ErrorMessage = ErrorMessageString,
                ValidationType = "requiredif",
            };
            rule.ValidationParameters["dependentproperty"] = (context as ViewContext).ViewData.TemplateInfo.GetFullHtmlFieldId(PropertyName);
            rule.ValidationParameters["desiredvalue"] = DesiredValue is bool ? DesiredValue.ToString().ToLower() : DesiredValue;

            yield return rule;
        }
    }

3.63
8
Phil_ish 80 points

                                    $.validator.unobtrusive.adapters.add('requiredif', ['dependentproperty', 'desiredvalue'], function (options) {
    options.rules['requiredif'] = options.params;
    options.messages['requiredif'] = options.message;
});

$.validator.addMethod('requiredif', function (value, element, parameters) {
    var desiredvalue = parameters.desiredvalue;
    desiredvalue = (desiredvalue == null ? '' : desiredvalue).toString();
    var controlType = $(&quot;input[id$='&quot; + parameters.dependentproperty + &quot;']&quot;).attr(&quot;type&quot;);
    var actualvalue = {}
    if (controlType == &quot;checkbox&quot; || controlType == &quot;radio&quot;) {
        var control = $(&quot;input[id$='&quot; + parameters.dependentproperty + &quot;']:checked&quot;);
        actualvalue = control.val();
    } else {
        actualvalue = $(&quot;#&quot; + parameters.dependentproperty).val();
    }
    if ($.trim(desiredvalue).toLowerCase() === $.trim(actualvalue).toLocaleLowerCase()) {
        var isValid = $.validator.methods.required.call(this, value, element, parameters);
        return isValid;
    }
    return true;
});

3.63 (8 Votes)
0
Are there any code examples left?
Create a Free Account
Unlock the power of data and AI by diving into Python, ChatGPT, SQL, Power BI, and beyond.
Sign up
Develop soft skills on BrainApps
Complete the IQ Test
Relative searches
ValidationAttribute in c# ValidationAttribute c# ValidationAttribute required validation model validation required attributes c# c# validation attribute required if validation decorator attribute method c# ValidationAttribute using validationattribute in mvc c# required vs [required()] c# data annotations c# required c# Required namespace define a class with required property c# class with compulsary input c# c# validations example c# optional required attribute c# dataannotations required c# required if imte in collection Validation attribute for required value c# require specific value attribute dotnet required attribute required data annotation c# asp.net class property is white visual studio asp.net class property is white visual studiui\ require specific attribute data annotation data annotation c# required specif error message in requiredif() annotation c# not working dataannotations c# Required change mesage of auto error mesage C# validationattribute c# context Required c# what is c# model validation Required null c# ValidationAttribute ex Model Validation c# c# how to make a required class c# class required property required model c# the Required attribute.c# add public property C# error message model required c# required attribute c# required attribute no error message property decorator validation c# declare a required field attribute C# data annotations required c# required attribute on memeber in object add required to c# property c# required attribute c# property required c# implication required annotaion vb net attributes for required field c# required attribute validation c# how to make a field required
Made with love
This website uses cookies to make IQCode work for you. By using this site, you agree to our cookie policy

Welcome Back!

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign in
Recover lost password
Or log in with

Create a Free Account

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign up
Or sign up with
By signing up, you agree to the Terms and Conditions and Privacy Policy. You also agree to receive product-related marketing emails from IQCode, which you can unsubscribe from at any time.
Creating a new code example
Code snippet title
Source