Home  >  Q&A  >  body text

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>
P粉124890778P粉124890778440 days ago498

reply all(2)I'll reply

  • P粉034571623

    P粉0345716232023-08-28 14:43:57

    The code above does illustrate this - only numbers are allowed. You can modify it by adding exceptions like this BACKSPACE

    
        
            
            
            sssccc
            
        
            
        
    
    

    reply
    0
  • P粉807471604

    P粉8074716042023-08-28 10:06:49

    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.

    $("input.number-only").bind({
        keydown: function(e) {
            if (e.shiftKey === true ) {
                if (e.which == 9) {
                    return true;
                }
                return false;
            }
            if (e.which > 57) {
                return false;
            }
            if (e.which==32) {
                return false;
            }
            return true;
        }
    });

    reply
    0
  • Cancelreply