ASP MVC Validate time
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)
Keep it simple. Use [Remote] validation attribute instead that you has created.
There's a example:
Model:
[DisplayName("Injury Time")]
[DataType(DataType.Time)]
[Remote("CheckTime", "Home", ErrorMessage = "Please check this field")]
[DisplayFormat(DataFormatString = "{0:hh:mm tt}", ApplyFormatInEditMode = true)]
public Nullable<System.DateTime> InjuryTime { get; set; }
Where Home is your controller.
Controller:
public ActionResult CheckTime(Nullable<System.DateTime> InjuryTime)
{
if (InjuryTime == something)
{
// This show the error message of validation
return Json(true, JsonRequestBehavior.AllowGet);
}
else
{
// This will ignore the validation
return Json(false, JsonRequestBehavior.AllowGet);
}
}
As simple like that. No modifications must to be done on the view. Feel free to ask.
链接地址: http://www.djcxy.com/p/56650.html上一篇: 为自定义ASP.NET MVC ValidationAttribute设置默认的ErrorMessage
下一篇: ASP MVC验证时间