Click here to Skip to main content
15,888,113 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i have a problem with the code for locking the keyboard and only allowing numeric values to be input
i have been trying the following code in the view

@Html.LabelFor(model => model.contactNo, new { @class = "control-label col-md-2" })

@Html.TextBoxFor(model => model.contactNo, new { @maxlength = "10", onkeypress = "return isNumberKey(event)" })

@Html.ValidationMessageFor(model => model.contactNo)


XML
<script type="text/javascript">

    function isNumberKey(evt) {
        var charCode = (evt.which) ? evt.which : event.keyCode;
        if (charCode != 46 && charCode > 31
          && (charCode < 48 || charCode > 57))
            return false;

        return true;
    }
</script>




but it doesn't work. it still allows the user to write letters and validate later
Posted

In mvc you can use data annotations in your data model to control the content that gets entered.
You place the annotations above the field property.
You can use regular express annotation to enforce numbers only ( i.e., [RegularExpression(@"^[0-9]*$")] ), this should not allow anything else to be entered in that field other than numeric digits.
You can also use the range annotation to set the range of values, ( i.e., [Range(1, 10)] ).

You should check out regular expressions.

You also have html helpers to show validation messages for the input ( i.e., textbox ).

In your javascript, you should be able to just check if(charCode >= 48 && charCode <= 57),
this adds the contraints to keep it between 0 and 9, you can see the difference between using AND and OR.
You can also use regular expressions in javascript.

Finally, check the syntax for proper use of quotes on parameters.
 
Share this answer
 
v5
In some versions of CSS3, you can create an INPUT item that only allows numbers - but not all browser will support this.

An always-works method would be to create an onchange event for the input box. Then, whenever a character is entered (or removed), you handler for the onchange event will go through the element's value and discard any non-numeric values. [Some methods for doing this were suggested in solution 1].

Then, use the result to update the input box's value;

 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900