Kevin Schultz
Kevin Schultz

Reputation: 884

Javascript to restrict entry to numbers in textbox

I have an MVC form that I want to restrict the entry on some textboxes to numbers only. I found this code that does that, however, it also restricts the use of the numbers on the keypad pad on the right of the keyboard. Any ideas on how to allow the keypad? I am not sure what is causing that to happen.

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

HTML Razor:

@Html.TextBoxFor(m => m.CustomerSSN, new { @placeholder = "Customer SSN", @type="number" })

Upvotes: 0

Views: 49

Answers (2)

Kevin Schultz
Kevin Schultz

Reputation: 884

So here is how I solved this...

<script type="text/javascript">
    //Allow only numbers entered
    $(document).ready(function () {
        $("#CustomerSSN").keypress(function (e) {
            if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
                                return false;
            }
        });
    });

Upvotes: 0

Phil Cazella
Phil Cazella

Reputation: 854

Another approach would be to use the HTML 5 input tag that has built in validation.

<input type="number" name="quantity">

www.w3schools.com/html/html_form_input_types.asp

Upvotes: 2

Related Questions