0

I have a textbox for proving username. But I want to restrict special characters over their when they are trying to type or trying to paste words(along with special characters). How can I do that by js. have written a code but in that only I can able to restrict the special characters over there during typing, but unable to restrict those characters when I paste some words over that textbox. My code is like:

<input type="text" name="bus_uname" id="bus_uname" class="reg-line-input"
  value="<?php echo ($back_uname!='')?$back_uname:'Business Username';?>"
  onblur="if(this.value=='') this.value='Business Username'"
  onFocus="if(this.value=='Business Username') this.value='';"
  onkeypress="return usernameonly(event, false)" />

and in js

function usernameonly(e, decimal) {
    var key;
    var keychar;

    if (window.event) {
       key = window.event.keyCode;
    }
    else if (e) {
       key = e.which;
    }
    else {
       return true;
    }
    keychar = String.fromCharCode(key);

    if ((key==null) || (key==0) || (key==8) ||  (key==9) || (key==13) || (key==27) ) {
       return true;
    }
    else if ((("!@#$%^&*()_+-=?/.><,';:").indexOf(keychar) > -1)) {
       return false;
    }
    //else
    //   return false;
}

Please help how to resolve this issue.

sundar
  • 45
  • 1
  • 6

1 Answers1

0
<input type="text" name="bus_uname" id="bus_uname" class="reg-line-input" value="<?php echo ($back_uname!='')?$back_uname:'Business Username';?>" onblur="if(this.value=='') this.value='Business Username'" onFocus="if(this.value=='Business Username') this.value='';" onkeypress="return usernameonly(event, false)" onpaste="return false" />

I added onpaste="return false" so that your users won't be able to paste and they must type the username.

rationalboss
  • 5,330
  • 3
  • 30
  • 50