How to restrict the textbox only accepts numeric values in MVC ?

Posted by Kasani007 under ASP.NET MVC on 8/7/2014 | Points: 10 | Views : 9101 | Status : [Member] | Replies : 2
How to restrict the textbox only accepts numeric values in MVC ?




Responses

Posted by: kgovindarao523-21772 on: 8/7/2014 [Member] [MVP] Bronze | Points: 25

Up
0
Down
You can use HTML5 input type number to restrict only number entries:

<input type="number" name="someid" />

This will work only in HTML5 complaint browser. Make sure your html document's doctype is:

<!DOCTYPE html>


For general purpose, you can have JS validation as below:

function isNumberKey(evt){

var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}

<input type="text" name="number" onkeypress="return isNumberKey(event)"/>

If you want to allow decimals replace the "if condition" with this:

if (charCode > 31 && (charCode != 46 &&(charCode < 48 || charCode > 57)))


Thank you,
Govind

Kasani007, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Goud.Kv on: 8/7/2014 [Member] [MVP] Gold | Points: 25

Up
0
Down
Good one.., But replace the below line in the above answer..
<input type="text" name="number" onkeypress="return isNumberKey(event)"/>

Then only it works..

Thanks & Regards,
Krishna

Kasani007, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response