How to prevent invalid characters from being typed into input fields

Asked
Active3 hr before
Viewed126 times

5 Answers

inputcharacterspreventinvalid
90%

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. ,it allows text and !"#$%& but you can adjust it adding these to the validationto only allow numbers by removing the ! in the return,Run your code against the onkeyup event and not the onkeydown event. This way you can access the result of the very last keystroke where as the onkeyup event executes as a key is pressed without knowing its result.

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;
   }
});
load more v
88%

The keydown event is fired when a key is pressed down. The event.key gives you information about what character was typed in, or in other words, what is going to appear in the <input>. So for character 2 you get event.key equal to 2 , for character á you get event.key equal to á.,Better alternative is keypress event. The keypress event is fired when a key that produces a character value is pressed down.,see keypress event fire,The keypress event should fire when a keypress produces a character value.

I needed to create an <input> that would accept only numbers and a slash symbol (/) - because pattern for birth number in Czech republic is xxxxxx/xxxx where all x are numbers. You can probably come up with many scenarios like this - e.g. in my country the commonly used date format is dd.mm.yyyy so an <input> that accepts only numbers and dots would be nice.

<input>

I needed to create an <input> that would accept only numbers and a slash symbol (/) - because pattern for birth number in Czech republic is xxxxxx/xxxx where all x are numbers. You can probably come up with many scenarios like this - e.g. in my country the commonly used date format is dd.mm.yyyy so an <input> that accepts only numbers and dots would be nice.

/

I needed to create an <input> that would accept only numbers and a slash symbol (/) - because pattern for birth number in Czech republic is xxxxxx/xxxx where all x are numbers. You can probably come up with many scenarios like this - e.g. in my country the commonly used date format is dd.mm.yyyy so an <input> that accepts only numbers and dots would be nice.

xxxxxx / xxxx

I needed to create an <input> that would accept only numbers and a slash symbol (/) - because pattern for birth number in Czech republic is xxxxxx/xxxx where all x are numbers. You can probably come up with many scenarios like this - e.g. in my country the commonly used date format is dd.mm.yyyy so an <input> that accepts only numbers and dots would be nice.

x

I needed to create an <input> that would accept only numbers and a slash symbol (/) - because pattern for birth number in Czech republic is xxxxxx/xxxx where all x are numbers. You can probably come up with many scenarios like this - e.g. in my country the commonly used date format is dd.mm.yyyy so an <input> that accepts only numbers and dots would be nice.

dd.mm.yyyy

I needed to create an <input> that would accept only numbers and a slash symbol (/) - because pattern for birth number in Czech republic is xxxxxx/xxxx where all x are numbers. You can probably come up with many scenarios like this - e.g. in my country the commonly used date format is dd.mm.yyyy so an <input> that accepts only numbers and dots would be nice.

<input>
load more v
72%

Onkeydown, I run the following JavaScript:,Code is useful for preventing user from typing any other character except number.,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. ,it allows text and !"#$%& but you can adjust it adding these to the validationto only allow numbers by removing the ! in the return

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;
   }
}

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]);
         }
      }

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

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

It is better to restrict the user from entering invalid input and submit the form.,If the inputted data is invalid then the request is not been executed on the server-side script if added validation and the user needs to again fill the details.,If a field does not require a specific type value like – number, character, special character then stop the user from entering.,You can also use it to restrict some of the characters or perform an action based on the character pressed e.g. when the enter key pressed you can submit your form.

Below script allows only number input.

$(document).ready(function() {
   $("#age").keypress(function(e) {
      var keyCode = e.which;
      /*
        8 - (backspace)
        32 - (space)
        48-57 - (0-9)Numbers
      */

      if ((keyCode != 8 || keyCode == 32) && (keyCode < 48 || keyCode > 57)) {
         return false;
      }
   });
});
load more v
75%

<input> elements of type text create basic single-line text fields.,This does not set a limit on how many characters the user can enter into the field. It only specifies approximately how many can be seen at a time. To set an upper limit on the length of the input data, use the maxlength attribute.,The example below restricts the value to 4-8 characters and requires that it contain only lower-case letters.,If you try to submit the form with no search term entered into it, the browser will show an error message.

let theText = myTextInput.value;
load more v

Other "input-characters" queries related to "How to prevent invalid characters from being typed into input fields"