How to allow only numbers (Numeric TextBox) in ASP.Net MVC using JavaScript

Last Reply on May 31, 2013 02:19 PM By ashusingh

Posted on May 19, 2013 11:03 PM

Hello,

I am developing an ASP .Net MVC 3 application using C# and SQL Server 2005.

I am using also Entity Framework and Code First Method.

I have some editor fields (text box) which I want to allow only user to put only Numbers in its.

Example :

 

<div><%:Html.Label("Nombre de Passage :")%><%: Html.EditorFor(model=>model.Nbr_Passage)%></div>

How can I restrict numeric in this textbox above ?

Posted on May 31, 2013 02:19 PM

Hi try the following....

HTML

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