How to allow only numbers in textbox in mvc4 razor

vaibhav shah picture vaibhav shah · Feb 6, 2013 · Viewed 227.3k times · Source

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 ?

Answer

hubson bropa picture hubson bropa · May 24, 2013

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