Last active
August 29, 2015 14:09
-
-
Save andyjansson/6d51d18682f5a0d49c13 to your computer and use it in GitHub Desktop.
LimitAttribute
This file contains 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
public class LimitAttribute : ValidationAttribute | |
{ | |
private int Limit {get; set;} | |
public LimitAttribute(int limit) | |
{ | |
this.Limit = limit; | |
} | |
public override bool IsValid(object value) | |
{ | |
if ((value != null) && !(value is ContentArea)) | |
{ | |
throw new ValidationException("LimitAttribute is intended only for use with ContentArea properties"); | |
} | |
var contentArea = value as ContentArea; | |
if (contentArea != null && contentArea.Items.Count() > Limit) | |
{ | |
ErrorMessage = "has too many items"; | |
return false; | |
} | |
return true; | |
} | |
protected override System.ComponentModel.DataAnnotations.ValidationResult IsValid(object value, System.ComponentModel.DataAnnotations.ValidationContext validationContext) | |
{ | |
var result = base.IsValid(value, validationContext); | |
if (result != null && !string.IsNullOrEmpty(result.ErrorMessage)) | |
{ | |
result.ErrorMessage = string.Format("{0} {1}", validationContext.DisplayName, ErrorMessage); | |
} | |
return result; | |
} | |
} |
This file contains 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
[Limit(3)] | |
public virtual ContentArea MainContentArea { get; set; } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment