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

我有3个文本框,取值邮政编码和手机号码和住宅号码。 我得到的解决方案,只允许数字在文本框使用 jquery 从贝娄帖子。

我想使编辑文本框只接受数字

但是我们能像使用 MVC4剃须刀一样使用数据注释吗?

270677 次浏览

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:

Masked Input Plugin

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

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.

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.

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

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.

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

Subscribe to onkeypress event for textbox.

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

Here is the javascript for it:

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

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

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

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)

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

and thanks to Lee Richardson, the c# way

@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

Use a regular expression, e.g.

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

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

This worked for me :

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

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

Please use the DataType attribute. This will accept negative values so the regular expression below will avoid this:

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

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

<input id="txtMyDecimal" min="0" step="any" type="number">
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;
}}
@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>
}

<input type="number" @bind="Quantity" class="txt2" />

Use the type="number"