Preventing invalid characters from being entered in fields: A comprehensive guide
<p><code>Onkeydown</code>, I run the following JavaScript: </p>
<pre class="brush:php;toolbar:false;">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;
}
}</pre>
<p>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! </p>
<p><strong>Edit</strong>: I create events globally. This is what I did:</p>
<pre class="brush:php;toolbar:false;">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]);
}
}</pre>
<p><code>globalization()</code>run<code>body.onload</code></p>
<p>So a typical input field has HTML and no function calls like this: </p>
<pre class="brush:php;toolbar:false;"><input id="AppFirstName" style="width: 150px;" type="text" maxlength="30" title="textonly"/> ;</pre>
<p><br /></p>