Skip to content

Instantly share code, notes, and snippets.

@ChrisMcKee
Created January 4, 2013 12:07
Show Gist options
  • Select an option

  • Save ChrisMcKee/4452157 to your computer and use it in GitHub Desktop.

Select an option

Save ChrisMcKee/4452157 to your computer and use it in GitHub Desktop.
UK Date format / Must be true (for T&C's) / Range "if"
namespace Helpers.Validators
{
using System.ComponentModel.DataAnnotations;
public class DateFormatAttribute : RegularExpressionAttribute
{
public DateFormatAttribute() : base(@"^((0[1-9])|([1-2][0-9])|3[0-1])\/((0[1-9])|(1[0-2]))\/[0-9]{4}$")
{
}
public override bool IsValid(object value)
{
return true;
}
}
public class EnforceTrueAttribute : ValidationAttribute
{
public override bool IsValid(object value)
{
return value != null
&& value is bool
&& (bool)value;
}
}
public class RangeIfAttribute : RangeAttribute
{
public string DependentProperty { get; set; }
public object TargetValue { get; set; }
public RangeIfAttribute(int minimum, int maximum, string dependentProperty , object targetValue) : base(minimum, maximum)
{
DependentProperty = dependentProperty;
TargetValue = targetValue;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var containerType = validationContext.ObjectInstance.GetType();
var field = containerType.GetProperty(DependentProperty);
if (field != null)
{
var dependentvalue = field.GetValue(validationContext.ObjectInstance, null);
if ((dependentvalue == null && TargetValue == null) || (dependentvalue != null && dependentvalue.Equals(TargetValue)))
{
if (!base.IsValid(value))
return new ValidationResult(ErrorMessage, new[] { validationContext.MemberName });
}
}
return ValidationResult.Success;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment