Skip to content

Instantly share code, notes, and snippets.

@Zabaa
Last active September 25, 2017 02:01
Show Gist options
  • Save Zabaa/19024f308d37320cc0a8a3890ca2b670 to your computer and use it in GitHub Desktop.
Save Zabaa/19024f308d37320cc0a8a3890ca2b670 to your computer and use it in GitHub Desktop.
[AttributeUsage(AttributeTargets.Property, AllowMultiple = true)]
public class RequiredIfEmptyAttribute : ValidationAttribute, IClientValidatable
{
private readonly string[] _dependentProperties;
public RequiredIfEmptyAttribute(params string[] dependentPropertieses)
{
_dependentProperties = dependentPropertieses;
}
public bool IsValid(object value, object dependentValue, object container)
{
if (string.IsNullOrEmpty((dependentValue ?? string.Empty).ToString().Trim()))
return value != null && !string.IsNullOrEmpty(value.ToString().Trim());
return true;
}
public override string FormatErrorMessage(string name)
{
if (string.IsNullOrEmpty(ErrorMessageResourceName) && string.IsNullOrEmpty(ErrorMessage))
ErrorMessage = _dependentProperties.Length > 1
? $"Pole jest wymagane jeśli pola {string.Join(",", _dependentProperties)} są puste"
: $"Pole jest wymagane jeśli pole {_dependentProperties.First()} jest puste";
return ErrorMessage;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
bool validate = true;
foreach (var dependentProperty in _dependentProperties)
{
var dependentValue = GetDependentPropertyValue(validationContext.ObjectInstance, dependentProperty);
validate = IsValid(value, dependentValue, validationContext);
if (!validate) break;
}
return validate
? ValidationResult.Success
: new ValidationResult(this.ErrorMessage, new[] { validationContext.MemberName });
}
private object GetDependentPropertyValue(object container, string dependentProperty)
{
var currentType = container.GetType();
var property = currentType.GetProperty(dependentProperty);
var value = property.GetValue(container, null);
return value;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule();
rule.ErrorMessage = FormatErrorMessage(metadata.GetDisplayName());
rule.ValidationParameters.Add("properties", string.Join(",", _dependentProperties));
rule.ValidationType = "requiredif";
yield return rule;
}
}
if ($.validator && $.validator.unobtrusive) {
$.validator.unobtrusive.adapters.add("requiredif", ["properties"], function(options) {
options.rules["requiredif"] = { properties: options.params["properties"] }
options.messages["requiredif"] = options.message;
});
$.validator.addMethod("requiredif", function (value, element, parameters) {
if (!value) {
var result = true;
var properties = parameters["properties"].split(",");
$.each(properties, function(index, property) {
var propertyObj = $("#" + property);
if (propertyObj.length === 0 || !propertyObj.val()) {
result = false;
}
});
return result;
}
return true;
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment