Click here to Skip to main content
14,843,683 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I use this javascript as a field validator
 <script type="text/javascript">
      //Function to allow only numbers to textbox
      function validate(key) {
          //getting key code of pressed key
          var keycode = (key.which) ? key.which : key.keyCode;
          var phn = document.getElementById('txtPhn');
          //comparing pressed keycodes
          if (!(keycode == 8 || keycode == 46) && (keycode < 48 || keycode > 57)) {
              return false;
          else {
              //Condition to check textbox contains ten numbers or not
              if (phn.value.length < 10) {
                  return true;
              else {
                  return false;

and add the function to the textbox
<asp:TextBox ID="txtTotal" runat="server" Width="131px" BorderStyle="None" Height="18px" onkeypress="return validate(event)"></asp:TextBox>

However, when the control is inside a gridview,

for example the textbox is inside the gridview, how do I call the onkeypress event?
DamithSL 11-May-14 22:10pm
you added event call to txtTotal but inside the function you validate on txtPhn, is there any reason for that?
JB0301 12-May-14 0:09am
my bad, I must have mistaken when I copied the code.

1 solution

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