首页 文章

ASP MVC验证时间

提问于
浏览
1

我正在尝试创建自定义数据注释时间验证器以验证日期时间字段 . 我希望它能在客户端验证 . 我在这个网站上找到了一个例子,但我认为它的一部分缺失了 . 我相信我创建的类部分工作,因为它似乎验证新创建的条目,但在Edit中不验证 . 我也在使用jquery-ui-timepicker-addon.js的timepicker .

I also have added this to my web.config 
 <add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />

我已经将jquery.validate.unobtrusive.js添加到我创建的timepicker包中 . 下面你会找到我的模型的一些部分,我创建的TimeAttribute类和我的Edit cshtml .
任何帮助深表感谢

[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)

1 回答

  • 0

    把事情简单化 . 使用[Remote]验证属性代替您创建的属性 .

    有一个例子:

    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; }
    

    家是你的控制者 .

    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);
                }
            }
    

    就像那样简单 . 不必对视图进行任何修改 . 随意问 .

相关问题