Click here to Skip to main content
15,908,661 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How to restrict characters in the asp.net textbox
i wrote the script but its not working,
whats wrong in the following code




JavaScript
function numberonly(event)
{
var numonly=(event.which) ? event.which : event.keyCode
if(numonly > 31 && (numonly < 97 || numonly > 122))
return true;         
return false;
}
Posted
Updated 20-Aug-10 2:34am
v2
Comments
R. Giskard Reventlov 20-Aug-10 8:24am    
You need to format the question and give a better title than your name or you'll never get an answer.

What is supposed to do your function?
if you want just digits then why don't you use the Char.IsDigit [^] method?
:)
 
Share this answer
 
Well Here is how I did it. You need to modify it to suit your needs

function allowOnlyDigit(evt, obj)
  {
    var charCode = (evt.which) ? evt.which : event.keyCode
    if (charCode == 45 ) 
    {
      var val = obj.value;      
      if(val.length > 0)
        return false;      
    }  
    else if (charCode > 31 && (charCode < 48) || (charCode > 57))
    {
      return false;
    }        
    return true;
  }




onkeypress="return allowOnlyDigit(event, this)"
 
Share this answer
 
You can use following JS Function :

function DisableSplChars(e) 
{
    var keynum
    var keychar
    var numcheck
    // For Internet Explorer
    if (window.event)
    {
        keynum = e.keyCode
    }
    // For Netscape/Firefox/Opera
    else if (e.which)
    {
        keynum = e.which
    }
    keychar = String.fromCharCode(keynum)
    //List of special characters you want to restrict
    if (keychar == "!" || keychar == "@" || keychar == "#"  
    || keychar == "$" || keychar == "%" || keychar == "^" || keychar == "&"
    || keychar == "*" || keychar == "(" || keychar == ")" 
    || keychar == "<" || keychar == ">")
    {
        return false;
    }
    else 
    {
        return true;
    }
}


And on Textbox you can call this javascript function

onkeypress="javascript:return DisableSplChars(event);"
 
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