Skip to content

Instantly share code, notes, and snippets.

@AlexCuse
Created December 18, 2012 22:13
Show Gist options
  • Save AlexCuse/4332562 to your computer and use it in GitHub Desktop.
Save AlexCuse/4332562 to your computer and use it in GitHub Desktop.
nullable integer validation
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