如何只允许mvc4 razor中的文本框中的数字

时间:2013-02-06 11:29:01

标签: asp.net-mvc asp.net-mvc-3 asp.net-mvc-4

我有3个文本框,它取值邮政编码&手机号码&住宅号码。 我使用来自Bellow post的jquery获得了仅允许文本框中的数字的解决方案。

I would like to make an EditFor textbox accept numbers only

但是我可以使用数据注释来实现这一点,因为我正在使用MVC4 razor吗?

16 个答案:

答案 0 :(得分:92)

我正在玩HTML5输入类型=数字。虽然它不受所有浏览器的支持,但我认为这是处理特定类型处理的方式(前面的数字)。用剃须刀很简单(ex是VB)

@Html.TextBoxFor(Function(model) model.Port, New With {.type = "number"})

感谢Lee Richardson,c#way

@Html.TextBoxFor(i => i.Port, new { @type = "number" }) 

超出了问题的范围,但您可以对任何html5输入类型执行相同的方法

答案 1 :(得分:54)

使用正则表达式,例如

[RegularExpression("([1-9][0-9]*)", ErrorMessage = "Count must be a natural number")]
public int Count { get; set; }

答案 2 :(得分:36)

@Html.TextBoxFor(m => m.PositiveNumber, 
                      new { @type = "number", @class = "span4", @min = "0" })

在使用Razor的MVC 5中,您可以在匿名对象中添加任何html输入属性,如上例所示,只允许在输入字段中使用正数。

答案 3 :(得分:14)

在文本框中编写此代码onkeypress="return isNumberKey(event)" 这个功能就在下面。

<script type="text/javascript">
function isNumberKey(evt)
{
          var charCode = (evt.which) ? evt.which : event.keyCode;
          if (charCode != 46 && charCode > 31 
            && (charCode < 48 || charCode > 57))
             return false;

          return true;
}
</script>

答案 4 :(得分:9)

请使用DataType attribue,但这将是否定值,因此下面的正则表达式将避免此

   [DataType(DataType.PhoneNumber,ErrorMessage="Not a number")]
   [Display(Name = "Oxygen")]
   [RegularExpression( @"^\d+$")]
   [Required(ErrorMessage="{0} is required")]
   [Range(0,30,ErrorMessage="Please use values between 0 to 30")]
    public int Oxygen { get; set; }

答案 5 :(得分:8)

这对我有用:

<input type="text" class="numericOnly" placeholder="Search" id="txtSearch">

Javacript:

//Allow users to enter numbers only
$(".numericOnly").bind('keypress', function (e) {
    if (e.keyCode == '9' || e.keyCode == '16') {
        return;
    }
    var code;
    if (e.keyCode) code = e.keyCode;
    else if (e.which) code = e.which;
    if (e.which == 46)
        return false;
    if (code == 8 || code == 46)
        return true;
    if (code < 48 || code > 57)
        return false;
});

//Disable paste
$(".numericOnly").bind("paste", function (e) {
    e.preventDefault();
});

$(".numericOnly").bind('mouseenter', function (e) {
    var val = $(this).val();
    if (val != '0') {
        val = val.replace(/[^0-9]+/g, "")
        $(this).val(val);
    }
});

答案 6 :(得分:5)

在脚本中使用此功能,并在文本框附近放置一个范围以显示错误消息

    $(document).ready(function () {
        $(".digit").keypress(function (e) {
            if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
                $("#errormsg").html("Digits Only").show().fadeOut("slow");
                return false;
            }
        });
   });

                            @Html.TextBoxFor(x => x.company.ContactNumber, new { @class = "digit" })
                            <span id="errormsg"></span>

答案 7 :(得分:3)

can we do this using data annotations as I am using MVC4 razor ?

不,正如我理解你的问题,不引人注意的验证只会显示出错误。最简单的方法是使用jquery插件:

Masked Input Plugin

答案 8 :(得分:2)

以下是允许您仅输入数字的JavaScript。

订阅onkeypress事件以获取文本框。

@Html.TextBoxFor(m=>m.Phone,new { @onkeypress="OnlyNumeric(this);"})

以下是javascript:

<script type="text/javascript">
function OnlyNumeric(e) {
            if ((e.which < 48 || e.which > 57)) {
                if (e.which == 8 || e.which == 46 || e.which == 0) {
                    return true;
                }
                else {
                    return false;
                }
            }
        }
</script>

希望它对你有所帮助。

答案 9 :(得分:1)

也许您可以使用[Integer]数据注释(如果您使用DataAnnotationsExtensions http://dataannotationsextensions.org/)。但是,这只会检查该值是否为整数,如果已填充则为n(如果您可能还需要[Required]属性)。

如果您启用Unobtrusive Validation,它将在客户端验证它,但您也应该在POST操作中使用Modelstate.Valid拒绝它,以防人们禁用Javascript。

答案 10 :(得分:1)

对于大于零的十进制值,HTML5的工作方式如下:

<input id="txtMyDecimal" min="0" step="any" type="number">

答案 11 :(得分:0)

DataType有第二个构造函数,它接受一个字符串。但是,在内部,这实际上与使用UIHint属性相同。

由于DataType枚举是.NET框架的一部分,因此无法添加新的核心DataType。您可以做的最接近的事情是创建一个继承自DataTypeAttribute的新类。然后,您可以使用自己的DataType枚举添加新构造函数。

public NewDataTypeAttribute(DataType dataType) : base(dataType)
 { }

public NewDataTypeAttribute(NewDataType newDataType) : base (newDataType.ToString();

您还可以浏览this链接。但我会建议你使用Jquery。

答案 12 :(得分:0)

嗨,请尝试以下内容....

<div class="editor-field">
  <%: Html.TextBoxFor(m => m.UserName, new {onkeydown="return ValidateNumber(event);" })%>
  <%: Html.ValidationMessageFor(m => m.UserName) %>
</div>

SCRIPT

<script type="text/javascript">
   function ValidateNumber(e) {
       var evt = (e) ? e : window.event;
       var charCode = (evt.keyCode) ? evt.keyCode : evt.which;
       if (charCode > 31 && (charCode < 48 || charCode > 57)) {
           return false;
       }
       return true;
   };

答案 13 :(得分:0)

function NumValidate(e) {
    var evt = (e) ? e : window.event;
    var charCode = (evt.keyCode) ? evt.keyCode : evt.which;
    if (charCode > 31 && (charCode < 48 || charCode > 57)) {
        alert('Only Number ');
        return false;
    }    return true;
}  function NumValidateWithDecimal(e) {

var evt = (e) ? e : window.event;
var charCode = (evt.keyCode) ? evt.keyCode : evt.which;

if (!(charCode == 8 || charCode == 46 || charCode == 110 || charCode == 13 || charCode == 9) && (charCode < 48 || charCode > 57)) {
    alert('Only Number With desimal e.g.: 0.0');
    return false;
}
else {
    return true;
} } function onlyAlphabets(e) {
try {
    if (window.event) {
        var charCode = window.event.keyCode;
    }
    else if (e) {
        var charCode = e.which;
    }
    else { return true; }

    if ((charCode > 64 && charCode < 91) || (charCode > 96 && charCode < 123) || (charCode == 46) || (charCode == 32))
        return true;
    else
        alert("Only text And White Space And . Allow");
    return false;

}
catch (err) {
    alert(err.Description);
}} function checkAlphaNumeric(e) {

if (window.event) {
    var charCode = window.event.keyCode;
}
else if (e) {
    var charCode = e.which;
}
else { return true; }

if ((charCode >= 48 && charCode <= 57) || (charCode >= 65 && charCode <= 90) || (charCode == 32) || (charCode >= 97 && charCode <= 122)) {
    return true;
} else {
    alert('Only Text And Number');
    return false;
}}

答案 14 :(得分:0)

@Html.TextBoxFor(x => x.MobileNo, new { @class = "digit" , @maxlength = "10"})

@section Scripts 
{
    @Scripts.Render("~/bundles/jqueryui")
    @Styles.Render("~/Content/cssjqryUi")

    <script type="text/javascript">
         $(".digit").keypress(function (e) {
            if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) 
            {
                $("#errormsg").html("Digits Only").show().fadeOut("slow");
                return false;
            }
         });
    </script>
}

答案 15 :(得分:0)

使用type =“ number”

相关问题