90

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.

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 ?

Community
  • 1
  • 1
vaibhav shah
  • 4,939
  • 19
  • 58
  • 96
  • 1
    you cannot do this because data annotations are called when you submit your form, not when you enter data to your textboxes – Karthik Chintala Feb 06 '13 at 12:35
  • while that is true, you can use the HTML5 input types validation rules (where supported by browser). works in this question scenario. – hubson bropa May 24 '13 at 16:40
  • Use jQuery with a css class –  Jul 23 '13 at 03:51
  • Possible duplicate of [Int or Number DataType for DataAnnotation validation attribute](http://stackoverflow.com/questions/4816822/int-or-number-datatype-for-dataannotation-validation-attribute) – KyleMit Feb 21 '17 at 18:26
  • @KarthikChintala That is incorrect. The data annotations are also used to when rendering the form, to determine client side jQuery validations and input types for various fields. – ProfK Mar 23 '17 at 07:44

16 Answers16

112

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

hubson bropa
  • 2,720
  • 2
  • 29
  • 35
67

Use a regular expression, e.g.

[RegularExpression("([1-9][0-9]*)", ErrorMessage = "Count must be a natural number")]
public int Count { get; set; }
Donal Lafferty
  • 5,807
  • 7
  • 43
  • 60
58
@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.

diegosasw
  • 13,734
  • 16
  • 95
  • 159
16

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>
Shwet
  • 1,848
  • 1
  • 24
  • 35
9

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; }
  
d219
  • 2,707
  • 5
  • 31
  • 36
TAHA SULTAN TEMURI
  • 4,031
  • 2
  • 40
  • 66
8

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);
    }
});
Deependra Singh
  • 161
  • 2
  • 8
  • This wont work on a lot of smartphones as the keypress event is not available on all mobiles. – Repo May 10 '16 at 11:55
8

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>
James Skemp
  • 8,018
  • 9
  • 64
  • 107
avc_004
  • 81
  • 1
  • 2
  • upvoted for simple solution .I don't know why they didn't marked it as answer working like charm – Mani Sep 02 '15 at 06:43
  • This wont work on a lot of smartphones as the keypress event is not available on all mobiles. – Repo May 10 '16 at 11:54
4

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

<input id="txtMyDecimal" min="0" step="any" type="number">
Chris J
  • 596
  • 1
  • 8
  • 14
3

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

webdeveloper
  • 17,174
  • 3
  • 48
  • 47
2

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.

Karthik Chintala
  • 5,465
  • 5
  • 30
  • 60
  • Not all Code paths return a value, and it doesn't work for me –  Jul 23 '13 at 03:03
  • This wont work on a lot of smartphones as the keypress event is not available on all mobiles. – Repo May 10 '16 at 11:56
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).

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.

Céryl Wiltink
  • 1,879
  • 11
  • 13
0

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.

Bhushan Firake
  • 9,338
  • 5
  • 44
  • 79
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;
   };
ar.gorgin
  • 4,765
  • 12
  • 61
  • 100
  • This wont work on a lot of smartphones as the keypress event is not available on all mobiles. – Repo May 10 '16 at 11:56
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>
}
Arun J
  • 687
  • 4
  • 14
  • 27
0

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

Use the type="number"

-1
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;
}}
  • 2
    how about a little description of your solution? – Jack Flamp Dec 08 '17 at 13:30
  • Usually it's better to explain a solution instead of just posting some rows of anonymous code. You can read [How do I write a good answer](https://stackoverflow.com/help/how-to-answer), and also [Explaining entirely code-based answers](https://meta.stackexchange.com/questions/114762/explaining-entirely-%E2%80%8C%E2%80%8Bcode-based-answers) – Anh Pham Dec 08 '17 at 13:45