如何防止用户输入错误的时间格式(客户端)

How to prevent a user from entering wrong time format(Client-side)

我的模型包含两个保存时间的属性。我想用户输入视图中的时间并防止它出现错误的值,例如 (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; }
}

可见

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

查看:

@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>

可以在以下位置找到该应用程序的工作示例:https://dotnetfiddle.net/6GpRBu 或者

  @Html.TextBoxFor(m => m.EndHour, new { @class = "form-control ", @type = "time" })

如果长度等于 5 文本框无法再获取值 型号

  [StringLength(5)]
  public string EndHour{ get; set;}