Search
 
SCRIPT & CODE EXAMPLE
 

CSHARP

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

C# ValidationAttribute required when

$.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 = $("input[id$='" + parameters.dependentproperty + "']").attr("type");
    var actualvalue = {}
    if (controlType == "checkbox" || controlType == "radio") {
        var control = $("input[id$='" + parameters.dependentproperty + "']:checked");
        actualvalue = control.val();
    } else {
        actualvalue = $("#" + parameters.dependentproperty).val();
    }
    if ($.trim(desiredvalue).toLowerCase() === $.trim(actualvalue).toLocaleLowerCase()) {
        var isValid = $.validator.methods.required.call(this, value, element, parameters);
        return isValid;
    }
    return true;
});
Comment

PREVIOUS NEXT
Code Example
Csharp :: C# top down view movement 
Csharp :: wpf change foreground c# 
Csharp :: how to detect ajax request in asp.net core 
Csharp :: flat view player movement script 
Csharp :: c# program exit 
Csharp :: unity collision.impulse 
Csharp :: extension method in c# 
Csharp :: how to check if an integer is in array c# 
Csharp :: How to decode Microsoft Local token in service 
Csharp :: Send Hotmail, Outlook, Office365 Email using SMTP C# .NET 
Csharp :: cant see my classes in inspector 
Csharp :: encrypt password easiest way in web app .net 
Csharp :: find gameobject by name in root 
Csharp :: use or in shell script 
Csharp :: unity change fixed timestep in code 
Csharp :: raq query ef core 
Csharp :: instantiate an array in c# 
Csharp :: print text c# unity 
Csharp :: check if list contains any empty element in c# 
Csharp :: console writeline 
Csharp :: c# while loops 
Csharp :: how to call last string from text file C# 
Csharp :: copy-the-entire-contents-of-a-directory-in-c-sharp 
Csharp :: serialize object to json 
Csharp :: c# exception middleware 
Csharp :: delete all fields that start with mongo 
Csharp :: what are delegates and how to use them c# 
Csharp :: how to use date range picker in asp.net C# 
Csharp :: unity SceneTemplatePipeline 
Csharp :: Read csv file into wpf C# 
ADD CONTENT
Topic
Content
Source link
Name
2+8 =