Onkeydown
, I run the following JavaScript:
function ThisOnKeyDown(el) { if (el.title == 'textonly') { !(/^[A-Za-zÑñ-s]*$/i).test(el.value) ? el.value = el.value.replace(/[^A-Za-zÑñ-s]/ig, '') : null; } if (el.title == 'numbersonly') { !(/^[0-9]*$/i).test(el.value) ? el.value = el.value.replace(/[^0-9]/ig, '') : null; } if (el.title == 'textandnumbers') { !(/^[A-Za-zÑñ0-9-s]*$/i).test(el.value) ? el.value = el.value.replace(/[^A-Za-zÑñ0-9-s ]/ig, '') : null; } }
One of these three title attributes is assigned to each input field on the page. The code works as long as the invalid characters are removed correctly, but not until the next character is entered. I'd like to find a way to simply reject invalid input. thanks for your help!
Edit: I create events globally. This is what I did:
function Globalization() { var inputs = document.getElementsByTagName('input'); for (i = 0; i < inputs.length; i ) { inputs[i].onfocus = createEventHandler( ThisOnFocus, inputs[i]); inputs[i].onblur = createEventHandler( ThisOnBlur, inputs[i]); inputs[i].onkeydown = createEventHandler( ThisOnKeyDown, inputs[i]); inputs[i].onkeyup = createEventHandler( ThisOnKeyUp, inputs[i]); } }
globalization()
runbody.onload
So a typical input field has HTML and no function calls like this:
;
The code above does illustrate this - only numbers are allowed. You can modify it by adding exceptions like this BACKSPACE
To prevent it from being set in the first place, you can return false on the keydown event handler, thus preventing the event from propagating further.
I wrote the example below using jQuery, but you can use the same function with traditional binding.
Although server-side validation is also important, client-side validation is also important for user-friendliness.