Rita
Rita

Reputation: 1237

How to enable only digits to enter into the Texbox on ASP.NET MVC Page?

I have an ASP.NET MVC Page along with Zipcode, Phonenumber & Fax.

Now i want to disable all other keys and only enable digits from the keyboard while typing on these textboxes.

Appreciate your responses.

As of now this is how the form is validated using Validation Plugin.

Zip*

    <td CssClass="Form_Value"><%= Html.TextBox("ZipCode", Model.AddressDetail.FirstOrDefault().ZipCode, new { @class = "required zip", minlength = "5"})%></td></tr>

$("#frmCustDetails").validate({

        rules: {
            ZipCode: {
                required: true, digits: true, minlength: 5, maxlength: 9 
         },
        messages: {
            ZipCode: {
                required: "please enter zipcode", digits: "please enter only digits", minlength: "Min is 5", maxlength: "Max is 9
       }
    });

Upvotes: 1

Views: 2588

Answers (3)

Kung Fu Ninja
Kung Fu Ninja

Reputation: 3752

Just FYI: keypress always returns 0 in FF. Please use keydown instead.

Upvotes: 1

Ryan Brunner
Ryan Brunner

Reputation: 14851

To prevent certain characters from being entered into a textbox, you can attach an onkeypress event to the textbox, and return false if the input recieved did not meet your expectations:

function validNumber(e) {
    keyPressed = e.keyCode;
    if (keyPressed < 48 || keyPressed > 57) {
       return false;
    }

    return true;
}

Upvotes: 1

Mattias Jakobsson
Mattias Jakobsson

Reputation: 8237

You can use a mask plugin, like this one. You should still validate it thought, both one the client side and on the server side.

Upvotes: 1

Related Questions