How to prevent invalid characters from being typed into input fields

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 given to various input fields on the page. The code works so far as invalid characters are correctly erased, but not until the next character is entered. I want to find a way to simply deny the invalid input in the first place. I appreciate your help!

Edit: I create the events globally. Here's how I do that:

      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() is run body.onload

Therefore, a typical input field has HTML without function calls like this:

          <input id="AppFirstName" style="width: 150px;" type="text" maxlength="30" title="textonly"/>

Solution 1:

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 any further.

I wrote the example below using jQuery, but you can use the same function when binding traditionally.

Though it's important to validate on the server-side as well, client-side validation is important for the sake of 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;
    }
});

Solution 2:

The above code does it says- allows ONLY numbers. You can modify it by adding exception to say BACKSPACE for example like this

<html>
    <head>
        <title></title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <script>
            function keyispressed(e){
                var charValue= String.fromCharCode(e.keyCode);
                if((isNaN(charValue)) && (e.which != 8 )){ // BSP KB code is 8
                    e.preventDefault();
                }
                return true;
            }
        </script>
    </head>    
    <body>
        <input type="text" onkeydown="return keyispressed(event);"/>
    </body>
</html>

Solution 3:

$('.key-filter').keypress(function () {
    if (event.key.replace(/[^\w\-.]/g,'')=='') event.preventDefault();
});

then add the key-filter class to your input if using jquery or

<input type="text" onkeypress="if (event.key.replace(/[^\w\-.]/g,'')=='') event.preventDefault();" />

just put the charaters you want to allow inside the [] after the ^. this allows all letters numbers _ - and .

Solution 4:

i found this solution in: http://help.dottoro.com/ljlkwans.php

works as intended.

<script type="text/javascript">
    function FilterInput (event) {
        var keyCode = ('which' in event) ? event.which : event.keyCode;

        isNumeric = (keyCode >= 48 /* KeyboardEvent.DOM_VK_0 */ && keyCode <= 57 /* KeyboardEvent.DOM_VK_9 */) ||
                    (keyCode >= 96 /* KeyboardEvent.DOM_VK_NUMPAD0 */ && keyCode <= 105 /* KeyboardEvent.DOM_VK_NUMPAD9 */);
        modifiers = (event.altKey || event.ctrlKey || event.shiftKey);
        return !isNumeric || modifiers;
    }
</script>

< body>
The following text field does not accept numeric input:
<input type="text" onkeydown="return FilterInput (event)" />< /body>

it allows text and !"#$%& but you can adjust it adding these to the validationto only allow numbers by removing the ! in the return