C# 如何防止用户输入错误的时间格式(客户端)
我的模型包含两个保持时间的属性。我希望用户输入视图中的时间,并防止其出现错误值,例如(07:66) 如果您知道JQuery中的一种方法,就可以屏蔽它C# 如何防止用户输入错误的时间格式(客户端),c#,asp.net-mvc,view,data-annotations,timespan,C#,Asp.net Mvc,View,Data Annotations,Timespan,我的模型包含两个保持时间的属性。我希望用户输入视图中的时间,并防止其出现错误值,例如(07:66) 如果您知道JQuery中的一种方法,就可以屏蔽它 public class WeeklyVW { [StringLength(5)] //or time span public string Ws_startTime { get; set; } [StringLength(5)] public string Ws_EndTime { get; set; } } 鉴于
public class WeeklyVW
{
[StringLength(5)]
//or time span
public string Ws_startTime { get; set; }
[StringLength(5)]
public string Ws_EndTime { get; set; }
}
鉴于
@Html.TextBoxFor(m => m.Starthour, new { data_mask = "00:00", @class = "form-control" })
通过使用
[DataType(DataType.Time)]
装饰模型属性,然后根据需要格式化时间输入字段,可以实现功能性。您需要做的第二件事是使用EditorFor
标记,而不是TextBoxFor
,这样才能工作。您的代码如下所示:
型号:
public class WeeklyVW
{
[StringLength(5)]
//or time span
public string Ws_startTime { get; set; }
[StringLength(5)]
public string Ws_EndTime { get; set; }
[Required]
[DataType(DataType.Time)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:HH}")]
public string Starthour {get;set;}
}
康特罗尔:
public ActionResult Index()
{
return View(new WeeklyVW());
}
视图:
如果长度等于5,文本框将无法获取更多值
模型
服务器端和客户端验证都是必需的。您可以使用正则表达式进行服务器端验证。@ManpritSinghSahota我想阻止视图中的用户您是否尝试将属性类型设置为
TimeSpan
?要添加到@ManpritSinghSahota,您必须在客户端(浏览器)上进行/should/validate验证,否则,您会发现恶棍会发送无效的时间,从而使您的站点崩溃。@Neil是的,只需在文本框中显示时间格式。我想阻止用户或向他显示输入错误的消息。
@model HelloWorldMvcApp.WeeklyVW
@{
Layout = null;
}
<!DOCTYPE html>
<!-- template from http://getbootstrap.com/getting-started -->
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Bootstrap 101 Template</title>
<!-- CSS Includes -->
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<style type="text/css">
.field-validation-error {
color: #ff0000;
}
</style>
</head>
<body>
<div class="container">
<div class="col-md-6 col-md-offset-3">
<h1>Time Input Example</h1>
@Html.EditorFor(m => m.Starthour, new { data_mask = "00:00", @class = "form-control" })
@Html.ValidationMessageFor(m => m.Starthour)
</div>
</div>
<!-- JS includes -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/mvc/4.0/jquery.validate.unobtrusive.min.js"></script>
</body>
</html>
@Html.TextBoxFor(m => m.EndHour, new { @class = "form-control ", @type = "time" })
[StringLength(5)]
public string EndHour{ get; set;}