TextBox 中始终有 5 位数字

Always have 5 digits in TextBox

我需要一个TextBox in ASP.NET MVC 这样它只能取5位数字,不多不少,如果输入的数字以0开头,那么显示的值在 TextBox 中以“0”开头。

示例,

因为我需要存储在数据库中,所以它在 TextBox 中是怎样的,我已经将该字段声明为 string

我假设您使用剃须刀语法中的@Html.Text 框。如果是这样,那么这应该适合你:

@Html.TextBox("FiveDigits", "", new { placeholder = "Enter 5 digits"})

会出现在您的视图中,而这会出现在您的控制器中:

 if (TheForm["FiveDigits"] > 99999 || TheForm["FiveDigits"] < 10000 || String.IsNullorEmpty(tablename.TextHasMoreThanFiveDigits))
    {
        ModelState.AddModelError("TextHasMoreThanFiveDigits", "You must enter a 5 digit number");
        return View(ViewWithTextBox);
    } else { do database stuff}

我不知道你的变量名称所以我编了一些,但我在我工作的程序中有非常相似的逻辑

您可以使用 minmax html 属性,但它们并非在所有浏览器中都强制执行,因此最好依赖 Javascript/jQuery.

$('.test-input').unbind('keyup change input paste').bind('keyup change input paste',function(e){
    var $this = $(this);
    var val = $this.val();
    var valLength = val.length;
    var maxCount = $this.attr('max');
    if(valLength>maxCount){
        $this.val($this.val().substring(0,maxCount));
    }
}); 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="test-input" type="number" max="5" />

此外,在用户输入值(keyup/change 事件)时检查最少字符数验证不是一个好的体验,因此最好在表单提交时检查它。