asp.net-mvc 如何在 mvc4 razor 中只允许文本框中的数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14727979/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 02:35:03  来源:igfitidea点击:

How to allow only numbers in textbox in mvc4 razor

asp.net-mvcasp.net-mvc-3asp.net-mvc-4

提问by vaibhav shah

I have 3 text box which takes values postal code & mobile number & residential number. I got the solution for allowing only number in text box using jquery from Bellow post.

我有 3 个文本框,其中包含邮政编码、手机号码和住宅号码。我得到了使用来自 Bellow post 的 jquery 只允许文本框中数字的解决方案。

I would like to make an EditFor textbox accept numbers only

我想让 EditFor 文本框只接受数字

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

但是我们可以在使用 MVC4 razor 时使用数据注释来做到这一点吗?

回答by hubson bropa

i was just playing around with HTML5 input type=number. while its not supported by all browsers I expect it is the way going forward to handle type specific handling (number for ex). pretty simple to do with razor (ex is VB)

我只是在玩 HTML5 输入类型=数字。虽然并非所有浏览器都支持它,但我希望它是处理特定于类型的处理(例如数字)的方法。使用剃刀非常简单(例如 VB)

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

and thanks to Lee Richardson, the c# way

并感谢 Lee Richardson,c# 方式

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

beyond the scope of the question but you could do this same approach for any html5 input type

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

回答by Donal Lafferty

Use a regular expression, e.g.

使用正则表达式,例如

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

回答by diegosasw

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

in MVC 5 with Razor you can add any html input attribute in the anonymous object as per above example to allow only positive numbers into the input field.

在带有 Razor 的 MVC 5 中,您可以按照上面的示例在匿名对象中添加任何 html 输入属性,以仅允许正数进入输入字段。

回答by Shwet

in textbox write this code onkeypress="return isNumberKey(event)"and function for this is just below.

在文本框中编写此代码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>

回答by TAHA SULTAN TEMURI

Please use DataType attribue but this will except negative values so the regular expression below will avoid this

请使用 DataType 属性,但这将排除负值,因此下面的正则表达式将避免这种情况

   [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; }

回答by Deependra Singh

This worked for me :

这对我有用:

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

Javacript:

Java脚本:

//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);
    }
});

回答by avc_004

Use this function in your script and put a span near textbox to show the error message

在脚本中使用此函数并在文本框附近放置一个跨度以显示错误消息

    $(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>

回答by webdeveloper

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

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

No, as I understand your question, unobtrusive validation will only show erorrs. The simplest way is use jquery plugin:

不,据我了解您的问题,不显眼的验证只会显示错误。最简单的方法是使用 jquery 插件:

Masked Input Plugin

屏蔽输入插件

回答by Karthik Chintala

Here is the javascript that will allows you to enter only numbers.

这是允许您仅输入数字的 javascript。

Subscribe to onkeypressevent for textbox.

订阅onkeypress文本框的事件。

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

Here is the javascript for it:

这是它的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>

Hope it helps you.

希望对你有帮助。

回答by Chris J

for decimal values greater than zero, HTML5 works as follows:

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

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