Skip to content

Instantly share code, notes, and snippets.

@alfeg
Created November 12, 2012 12:29
Show Gist options
  • Save alfeg/4059091 to your computer and use it in GitHub Desktop.
Save alfeg/4059091 to your computer and use it in GitHub Desktop.
RequiredIf
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
namespace KI.Web.Admin.Common.Validation
{
public class RequiredIfGreaterValidator : DataAnnotationsModelValidator<RequiredIfGreaterAttribute>
{
public RequiredIfGreaterValidator(ModelMetadata metadata, ControllerContext context, RequiredIfGreaterAttribute greaterAttribute)
: base(metadata, context, greaterAttribute)
{
}
private const string validationType = "RequiredIfGreater";
public override IEnumerable<ModelClientValidationRule>GetClientValidationRules()
{
var rule = new ModelClientValidationRule
{
ErrorMessage = Attribute.ErrorMessage,
ValidationType = validationType
};
rule.ValidationParameters.Add("dependent", Attribute.DependentProperty);
rule.ValidationParameters.Add("targetValue", Attribute.TargetValue);
return new[] { rule };
}
public override IEnumerable<ModelValidationResult> Validate(object container)
{
// get a reference to the property this validation depends upon
var field = Metadata.ContainerType.GetProperty(Attribute.DependentProperty);
if (field != null)
{
// get the value of the dependent property
var value = field.GetValue(container, null);
// convert values to target type
var sourceValue = Convert.ChangeType(value, Attribute.Type) as IComparable;
var attributeValue = Convert.ChangeType(Attribute.TargetValue, Attribute.Type) as IComparable;
if((sourceValue == null || attributeValue == null) // if any of fields are not specified, or not comparable, then force require validation
|| sourceValue.CompareTo(attributeValue) == 1)
{
// this field need require validation
if (!Attribute.IsValid(Metadata.Model))
yield return new ModelValidationResult { Message = ErrorMessage };
}
}
}
}
public class RequiredIfGreaterAttribute : ValidationAttribute
{
// Note: we don't inherit from RequiredAttribute as some elements of the MVC
// framework specifically look for it and choose not to add a RequiredValidator
// for non-nullable fields if one is found. This would be invalid if we inherited
// from it as obviously our RequiredIf only applies if a condition is satisfied.
// Therefore we're using a private instance of one just so we can reuse the IsValid
// logic, and don't need to rewrite it.
private readonly RequiredAttribute innerAttribute = new RequiredAttribute();
public string DependentProperty { get; set; }
public object TargetValue { get; set; }
public Type Type { get; set; }
public RequiredIfGreaterAttribute(string dependentProperty, object targetValue)
{
this.DependentProperty = dependentProperty;
this.TargetValue = targetValue;
}
public override bool IsValid(object value)
{
return innerAttribute.IsValid(value);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment