Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to allow only numbers in textbox in mvc4 razor

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 ?

like image 714
vaibhav shah Avatar asked Feb 06 '13 11:02

vaibhav shah


People also ask

How do I allow only numbers in a text box?

The standard solution to restrict a user to enter only numeric values is to use <input> elements of type number. It has built-in validation to reject non-numerical values.

How do you make a text box readonly in razor?

In razor, everything is easy just add @readonly attribute to the code will do the needful. Hope this helps you a bit.

What is the difference between using HTML TextBoxFor and HTML TextBox?

Both of them provide the same HTML output, “HTML. TextBoxFor” is strongly typed while “HTML. TextBox” isn't. Below is a simple HTML code which just creates a simple textbox with “CustomerCode” as name.


2 Answers

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

like image 172
hubson bropa Avatar answered Oct 11 '22 16:10

hubson bropa


Use a regular expression, e.g.

[RegularExpression("([1-9][0-9]*)", ErrorMessage = "Count must be a natural number")] public int Count { get; set; } 
like image 27
Donal Lafferty Avatar answered Oct 11 '22 17:10

Donal Lafferty