Created
February 18, 2011 13:17
-
-
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
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; | |
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