如何只允许文本框中的数字在mvc4剃刀

时间:2021-12-24 04:02:27

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

我想对文本框进行编辑,只接受数字。

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

但是我们可以在使用MVC4 razor时使用数据注释吗?

14 个解决方案

#1


76  

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输入类型=number。虽然不是所有浏览器都支持它,但我希望它是处理类型特定处理的方式(例如,number for ex)。使用razor非常简单(ex是VB)

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

and thanks to Lee Richardson, the c# way

感谢李·理查森,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输入类型执行相同的方法

#2


47  

Use a regular expression, e.g.

使用正则表达式,例如。

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

#3


34  

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

在MVC 5中,使用Razor,你可以在匿名对象中添加任何html输入属性,就像上面的例子一样,只允许在输入字段中加入正数。

#4


13  

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>

#5


8  

This worked for me :

这对我很有效:

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

Javacript:

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


6  

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

请使用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; }

#7


4  

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

在脚本中使用此函数,并在文本框附近放置span以显示错误消息

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

#8


3  

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

我们是否可以像使用MVC4 razor那样使用数据注释来实现这一点?

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

不,我理解你的问题,不引人注目的验证只会显示erorrs。最简单的方法是使用jquery插件:

Masked Input Plugin

蒙面输入插件

#9


2  

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

这里是将允许您只输入数字的javascript。

Subscribe to onkeypress event 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.

希望它能帮助你。

#10


1  

Maybe you can use the [Integer] data annotation (If you use the DataAnnotationsExtensions http://dataannotationsextensions.org/) . However, this wil only check if the value is an integer, nót if it is filled in (So you may also need the [Required] attribute).

也许您可以使用[Integer]数据注释(如果您使用dataannotationsextense http://dataannotationsextensions.org/)。但是,这个wil只检查值是否是整数,而不检查它是否被填充(因此您可能还需要[Required]属性)。

If you enable Unobtrusive Validation it will validate it clientside, but you should also use Modelstate.Valid in your POST action to decline it in case people have Javascript disabled.

如果您启用不显眼的验证,它将验证它clientside,但是您也应该使用Modelstate。在您的POST操作中有效,可以在禁用Javascript的情况下拒绝它。

#11


0  

DataType has a second constructor that takes a string. However, internally, this is actually the same as using the UIHint attribute.

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

Adding a new core DataType is not possible since the DataType enumeration is part of the .NET framework. The closest thing you can do is to create a new class that inherits from the DataTypeAttribute. Then you can add a new constructor with your own DataType enumeration.

添加新的核心数据类型是不可能的,因为数据类型枚举是. net框架的一部分。您可以做的最接近的事情是创建一个从DataTypeAttribute继承的新类。然后可以使用自己的数据类型枚举添加一个新的构造函数。

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

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

You can also go through this link. But I will recommend you using Jquery for the same.

你也可以通过这个链接。但是我也建议您使用Jquery。

#12


0  

Hi try the following....

嗨,尝试以下....

<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  

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

对于大于0的小数,HTML5的工作原理如下:

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

#14


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

#1


76  

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输入类型=number。虽然不是所有浏览器都支持它,但我希望它是处理类型特定处理的方式(例如,number for ex)。使用razor非常简单(ex是VB)

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

and thanks to Lee Richardson, the c# way

感谢李·理查森,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输入类型执行相同的方法

#2


47  

Use a regular expression, e.g.

使用正则表达式,例如。

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

#3


34  

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

在MVC 5中,使用Razor,你可以在匿名对象中添加任何html输入属性,就像上面的例子一样,只允许在输入字段中加入正数。

#4


13  

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>

#5


8  

This worked for me :

这对我很有效:

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

Javacript:

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


6  

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

请使用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; }

#7


4  

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

在脚本中使用此函数,并在文本框附近放置span以显示错误消息

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

#8


3  

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

我们是否可以像使用MVC4 razor那样使用数据注释来实现这一点?

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

不,我理解你的问题,不引人注目的验证只会显示erorrs。最简单的方法是使用jquery插件:

Masked Input Plugin

蒙面输入插件

#9


2  

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

这里是将允许您只输入数字的javascript。

Subscribe to onkeypress event 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.

希望它能帮助你。

#10


1  

Maybe you can use the [Integer] data annotation (If you use the DataAnnotationsExtensions http://dataannotationsextensions.org/) . However, this wil only check if the value is an integer, nót if it is filled in (So you may also need the [Required] attribute).

也许您可以使用[Integer]数据注释(如果您使用dataannotationsextense http://dataannotationsextensions.org/)。但是,这个wil只检查值是否是整数,而不检查它是否被填充(因此您可能还需要[Required]属性)。

If you enable Unobtrusive Validation it will validate it clientside, but you should also use Modelstate.Valid in your POST action to decline it in case people have Javascript disabled.

如果您启用不显眼的验证,它将验证它clientside,但是您也应该使用Modelstate。在您的POST操作中有效,可以在禁用Javascript的情况下拒绝它。

#11


0  

DataType has a second constructor that takes a string. However, internally, this is actually the same as using the UIHint attribute.

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

Adding a new core DataType is not possible since the DataType enumeration is part of the .NET framework. The closest thing you can do is to create a new class that inherits from the DataTypeAttribute. Then you can add a new constructor with your own DataType enumeration.

添加新的核心数据类型是不可能的,因为数据类型枚举是. net框架的一部分。您可以做的最接近的事情是创建一个从DataTypeAttribute继承的新类。然后可以使用自己的数据类型枚举添加一个新的构造函数。

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

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

You can also go through this link. But I will recommend you using Jquery for the same.

你也可以通过这个链接。但是我也建议您使用Jquery。

#12


0  

Hi try the following....

嗨,尝试以下....

<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  

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

对于大于0的小数,HTML5的工作原理如下:

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

#14


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