I am trying to create a custom data annotations time validator to validate a datetime time field. I would like it to validate on the client. I found an example to follow on this site but I think part of it is missing. I do believe that the class I created is partially working because it seems to be validating newly created entries but does not validate when in Edit. Also I am using a timepicker with jquery-ui-timepicker-addon.js.
I also have added this to my web.config
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
And I have added jquery.validate.unobtrusive.js" to the timepicker bundle I created.
Below you will find bits of my model, the TimeAttribute class I created and my Edit cshtml.
Any help is much appreciated
[DisplayName("Injury Time")]
[DataType(DataType.Time)]
[Time]
[DisplayFormat(DataFormatString = "{0:hh:mm tt}", ApplyFormatInEditMode = true)]
public Nullable<System.DateTime> InjuryTime { get; set; }
` public class TimeAttribute : ValidationAttribute, IClientValidatable { public IEnumerable GetClientValidationRules(ModelMetadata metadata, ControllerContext context) { yield return new ModelClientValidationRule { ErrorMessage = ErrorMessage, ValidationType = "time" }; }
public override bool IsValid(object value)
{
DateTime time;
if (value == null || !DateTime.TryParse(value.ToString(), out time))
return false;
return true;
}
}
`
@Html.LabelFor(model => model.InjuryTime, new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.InjuryTime)
@Html.ValidationMessageFor(model => model.InjuryTime)