Created
January 4, 2013 12:07
-
-
Save ChrisMcKee/4452157 to your computer and use it in GitHub Desktop.
UK Date format / Must be true (for T&C's) / Range "if"
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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