Created
December 18, 2012 22:13
-
-
Save AlexCuse/4332562 to your computer and use it in GitHub Desktop.
nullable integer validation
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
using System.ComponentModel.DataAnnotations; | |
namespace Project.MvvmFramework.ValidationAttributes | |
{ | |
public class NullableIntegerAttribute : ValidationAttribute | |
{ | |
private readonly int _maxDigits; | |
private readonly string _propertyName; | |
const string MessageFormat = "{0} can only contain up to {1} numeric characters."; | |
public NullableIntegerAttribute(int maxDigits, string propertyName) | |
{ | |
_maxDigits = maxDigits; | |
_propertyName = propertyName; | |
} | |
protected override ValidationResult IsValid(object value, ValidationContext validationContext) | |
{ | |
var propertyInfo = validationContext.ObjectType.GetProperty(_propertyName); | |
var retrievedValue = propertyInfo.GetValue(validationContext.ObjectInstance, null) as string; | |
long parsed; | |
if (string.IsNullOrEmpty(retrievedValue) || (retrievedValue.Length <= _maxDigits && long.TryParse(retrievedValue, out parsed))) | |
{ | |
return ValidationResult.Success; | |
} | |
return new ValidationResult(string.Format(MessageFormat, _propertyName, _maxDigits)); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment