How to avoid special characters on key press – javascript

Avoid keying of special characters.. hope this doesn’t need any explanation…


<input type="text" onkeypress="avoidSplChars(event)" />


 
function avoidSplChars(e) {
 e = e || window.event;
 var bad = /[^\sa-z\d]/i,
 key = String.fromCharCode( e.keyCode || e.which );

    if ( e.which !== 0 && e.charCode !== 0 && bad.test(key) ) {
          e.returnValue = false;
          if ( e.preventDefault ) {
              e.preventDefault(); 
          }
    } 
}
 

Happy Kooding… hope this helps!!


					
Advertisements