Skip to content

Instantly share code, notes, and snippets.

@shibayan
Created May 16, 2013 05:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shibayan/5589515 to your computer and use it in GitHub Desktop.
Save shibayan/5589515 to your computer and use it in GitHub Desktop.
public class DateAttribute : DataTypeAttribute
{
public DateAttribute()
: base(DataType.Date)
{
}
public string MonthProperty { get; set; }
public string DateProperty { get; set; }
public string EmptyErrorMessage { get; set; }
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var monthProperty = validationContext.ObjectType.GetProperty(MonthProperty);
var dayProperty = validationContext.ObjectType.GetProperty(DateProperty);
var year = (string)value;
var month = (string)monthProperty.GetValue(validationContext.ObjectInstance);
var date = (string)dayProperty.GetValue(validationContext.ObjectInstance);
if (string.IsNullOrEmpty(year) || string.IsNullOrEmpty(month) || string.IsNullOrEmpty(date))
{
return new ValidationResult(EmptyErrorMessage);
}
DateTime result;
if (!DateTime.TryParseExact(year + "/" + month + "/" + date, "yyyy/M/d", null, DateTimeStyles.None, out result))
{
return new ValidationResult(ErrorMessageString);
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment