How to allow only numbers in textbox in mvc4 razor

asp.net Mvcasp.net Mvc-3asp.net Mvc-4

asp.net Mvc Problem Overview


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.

https://stackoverflow.com/questions/7310796/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 ?

asp.net Mvc Solutions


Solution 1 - asp.net Mvc

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

Solution 2 - asp.net Mvc

Use a regular expression, e.g.

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

Solution 3 - asp.net Mvc

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

Solution 4 - asp.net Mvc

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>

Solution 5 - asp.net Mvc

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

Solution 6 - asp.net Mvc

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

Solution 7 - asp.net Mvc

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>

Solution 8 - asp.net Mvc

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

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

Solution 9 - asp.net Mvc

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

Solution 10 - asp.net Mvc

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.

Solution 11 - asp.net Mvc

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.

Solution 12 - asp.net Mvc

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.

Solution 13 - asp.net Mvc

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

Solution 14 - asp.net Mvc

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

Solution 15 - asp.net Mvc

Use the type="number"

Solution 16 - asp.net Mvc

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionvaibhav shahView Question on Stackoverflow
Solution 1 - asp.net Mvchubson bropaView Answer on Stackoverflow
Solution 2 - asp.net MvcDonal LaffertyView Answer on Stackoverflow
Solution 3 - asp.net MvcdiegosaswView Answer on Stackoverflow
Solution 4 - asp.net MvcShwetView Answer on Stackoverflow
Solution 5 - asp.net MvcTAHA SULTAN TEMURIView Answer on Stackoverflow
Solution 6 - asp.net MvcDeependra SinghView Answer on Stackoverflow
Solution 7 - asp.net Mvcavc_004View Answer on Stackoverflow
Solution 8 - asp.net MvcChris JView Answer on Stackoverflow
Solution 9 - asp.net MvcwebdeveloperView Answer on Stackoverflow
Solution 10 - asp.net MvcKarthik ChintalaView Answer on Stackoverflow
Solution 11 - asp.net MvcCéryl WiltinkView Answer on Stackoverflow
Solution 12 - asp.net MvcBhushan FirakeView Answer on Stackoverflow
Solution 13 - asp.net Mvcar.gorginView Answer on Stackoverflow
Solution 14 - asp.net Mvcrasika kaleView Answer on Stackoverflow
Solution 15 - asp.net MvcAshandra SinghView Answer on Stackoverflow
Solution 16 - asp.net MvcGautam PrajapatiView Answer on Stackoverflow