Skip to content

Instantly share code, notes, and snippets.

@jakejscott
Created February 18, 2011 13:17
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 jakejscott/833637 to your computer and use it in GitHub Desktop.
Save jakejscott/833637 to your computer and use it in GitHub Desktop.
DateTimeAttribute allows you to validate a string property on a DTO as if it was a date
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public sealed class DateAttribute : DataTypeAttribute, IClientValidatable
{
public DateAttribute() : base(DataType.DateTime)
{
ErrorMessage = "The {0} field is not a valid date.";
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
yield return new ModelClientValidationRule
{
ValidationType = "date",
ErrorMessage = FormatErrorMessage(metadata.GetDisplayName())
};
}
public override bool IsValid(object value)
{
if (value == null)
{
return true;
}
DateTime valueAsDate;
string valueAsString = value as string;
return valueAsString != null && DateTime.TryParse(valueAsString, out valueAsDate);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment