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

时间:2019-07-10 08:56:37

标签: 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; }
}

可见

@Html.TextBoxFor(m => m.Starthour, new { data_mask = "00:00", @class = "form-control" })

1 个答案:

答案 0 :(得分:0)

您可以通过用[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;}