Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

prevent input of special chars with alt + number pad in a text input with javascript

Status
Not open for further replies.

Stefan Houtzager

Programmer
Jan 21, 2019
1
NL
Hi,

I'm new here. I want to prevent the input of for example an é character with alt130 or strange chars like ☻ (alt2) in a text input. This seems difficult ( I could not do it with preventdefault in a keydown or keyup event. Tips?

Thanks, Stefan.

Edit:
Found a solution, works in the newest version of chrome at least
element.onkeydown = e => {
element.altKeyDown = e.altKey;
element.oldValue = element.value;
etc.

element.oninput = () => {
if (element.altKeyDown) {
let cursorPosition = element.selectionStart - 1;
element.value = element.oldValue;
element.selectionStart = cursorPosition;
element.selectionEnd = cursorPosition;
}
}
 
there are a few options here, you can :

1. check on keypress as you are now
2. check on leaving the field - use the ONBLUR event on the field
3. check on form submission - use ONSUBMIT

for the test itself, if you only want standard ASCII chars, then you should be able to use a Regular Expression or some JS checks.

In all cases, I would also recommend validation on the server side for security.

Greg Griffiths
Livelink Certified Developer & ECM Global Star Champion 2005 & 2006
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top