How to Prevent Character Input Javascript

In this tutorial I will share how to prevent character input Javascript.

I’ve included three types of keyboard text input filtering:

1️⃣ Digits only

2️⃣ Letters only

3️⃣ User’s custom characters set

Preventing invalid characters input may become useful in variety of cases, for example phone or bank card number. In eCommerce each product may have a unique index (ex: EA-00912), etc.

As a UI designer, I decided to style keyboard input filtering in Dark Mode UI style.

So, let’s go and see the project in action below ⬇️

Project: Keyboard Text Input Filtering

// prevent character input javascript

In this CodePen user can choose set of characters that is allowed to type.

See the Pen Keyboard Input Filter JS by jsSecrets (@jssecrets) on CodePen.

In that CodePen we have a determined set of characters – digits.

[0,1,2,3,4,5,6,7,8,9,]

User can chooses to allow or disallow input of that set.

See the Pen Allow / Disallow Characters Input JS by jsSecrets (@jssecrets) on CodePen.

prevent character input js
prevent character input js

Basic Working Principle

// prevent character input javascript

What is Keyboard Input Filter in a nutshell?

// prevent character input javascript

Let’s say we have a set of characters for hexadecimal numeral system.

Which is [0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F].

In our imaginary app each new user can pick a background color in HEX format (ex: #00FFA3) for his profile. And he must enter the value to user input from the keyboard.

By the standard only characters from the hexadecimal set must be used.

So, when a user presses the key on a keyboard our app performs a check.

If a character belongs to the set, then allow the input, otherwise prevents input of invalid characters.

prevent character input javascript
prevent character input javascript

Working Principle

// prevent character input javascript

Simplest Working Version (SWV)

// prevent character input javascript

In my view, the SWV of keyboard input filter is HTML <input> with type “number” attribute:

<input type="number" />

It allows only digits and “.” (period) symbol on keypress event to be entered to user input.

Core concept

// prevent character input javascript

Let’s start with core concept of how to prevent character input Javascript works.

1️⃣ HTML

// how to prevent character input in javascript

HTML consists of three parts:

1️⃣ <input> to test regular expressions

2️⃣ .tabs to switch between different regular expressions

3️⃣ <input> for custom regular expressions (hidden by default)

2️⃣ CSS

// how to prevent character input in javascript

CSS contains only basic styling. Nothing special in this project.

3️⃣ Javascript

// how to prevent character input in javascript

Almost each keyboard input filter is connected with regular expressions. So, there are plenty in this project.

JS code contains following functions:

1️⃣ setActiveTab() – to switch between sliding tabs to select regEx

2️⃣ inputFilter() – catches pressed key to prevent unwanted on keypress event

3️⃣ inputUserChoice() – to set user’s regular expression

4️⃣ ifEmpty() – check whether the user input is empty

prevent character input javascript
prevent character input javascript

Code explanation

// how to prevent character input in javascript

If you have understood the core concept and working principle of how to keyboard input filter JS is built, the code will be easy to grasp.

HTML

// prevent character input js

<body>

    <!-- tabs -->
    <div class="input-settings">
      <ul class="tabs">
        <li class="tab digits active">
          <span class="title">Digits</span>
        </li>
        <li class="tab letters">
          <span class="title">Letters</span>
        </li>
        <li class="tab yours">
          <span class="title">Yours</span>
        </li>
        <div class="slider"></div>
      </ul>
    </div>
    <!-- END tabs -->

    <!-- custom regular expression input -->
    <!-- hidden by default -->
    <div class="my-reg-ex-container">
      <input class="my-reg-ex" type="text" />
    </div>
    <!--END custom regular expression input -->

    <!-- input -->
    <input class="primary" type="text" />
    <!--END input -->

</body>

CSS

// prevent character input js

/* basic reset */
*,
::before,
::after {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: "Poppins", sans-serif;
}

ul {
  list-style: none;
}

body {
  height: 100vh;
  background: hsl(225, 14%, 12%);
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;
  color: #292d34;
}

/* user input field */
input.primary {
  width: 320px;
  border: 2px solid rgb(80, 121, 247);
  box-shadow: 0 4px 20px rgba(80, 121, 247, 0.4);
  color: rgb(80, 121, 247);
  background: transparent;
  outline: none;
  font-size: 24px;
  padding: 16px;
  border-radius: 12px;
  transition: all 0.8s ease-out;
  opacity: 1;
}
@media (max-width: 400px) {
  input.primary {
    width: 220px;
    padding: 8px;
  }
}

/* tabs container */
.input-settings {
  width: 320px;
  border-radius: 10px;
  background-color: hsl(225, 14%, 17%);
  border: 1.5px solid rgba(0, 0, 0, 0.38);
  box-shadow: 0 8px 32px 0 hsl(225, 14%, 12%);
  backdrop-filter: blur(40px);
  padding: 16px;
  position: absolute;
  left: 50%;
  top: 5%;
  transform: translate(-50%, -5%);
  opacity: 1;
  transition: all 0.7s ease-out;
}
@media (max-width: 400px) {
  .input-settings {
    width: 220px;
    padding: 8px;
  }
}

/* custom regular expression container */
.my-reg-ex-container {
  position: absolute;
  left: 50%;
  top: 18%;
  transform: translate(-50%, -5%);
  width: 320px;
  transition: all 0.5s ease-out;
}
@media (max-width: 400px) {
  .my-reg-ex-container {
    width: 220px;
  }
}

/* custom regular expression input */
.my-reg-ex-container .my-reg-ex {
  width: 100%;
  border-radius: 10px;
  border: 2px solid #f7ce51;
  box-shadow: 0 4px 20px rgba(245, 205, 81, 0.4);
  color: #f7ce51;
  background: transparent;
  outline: none;
  font-size: 24px;
  padding: 16px;
  border-radius: 12px;
  transition: all 0.5s ease-out;
  opacity: 0;
  transform: translateY(-20px);
}
@media (max-width: 400px) {
  .my-reg-ex-container .my-reg-ex {
    padding: 8px;
  }
}
.my-reg-ex-container.active .my-reg-ex {
  opacity: 1;
  transform: translateY(0);
}

/* tabs */
/* learn how to build tabs in detailed tutorial: */
/* http://jssecrets.com/how-to-build-sliding-tabs-javascript/ */
.tabs {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
}
.tabs .slider {
  position: absolute;
  left: 0;
  bottom: 0;
  height: 100%;
  width: 33.33333%;
  background: linear-gradient(45deg, rgb(245, 205, 81) 0%, rgb(247, 206, 81) 100%);
  box-shadow: 0 4px 20px rgba(245, 205, 81, 0.4);
  border-radius: 9px;
  z-index: 0;
  transition: all 0.3s linear;
}
.tabs .tab {
  width: 50%;
  height: 100%;
  display: block;
  text-align: center;
  cursor: pointer;
  padding: 16px 0 16px 0;
  border-radius: 9px;
  font-size: 16px;
  z-index: 1;
  position: relative;
  color: #7c828d;
  transition: all 0.3s linear;
}
.tabs .tab:hover {
  color: #f7ce51;
}
.tabs .tab .title {
  font-size: 16px;
}
@media (max-width: 400px) {
  .tabs .tab .title {
    font-size: 14px;
  }
}
.tabs .tab.active .title {
  font-weight: 900;
  color: hsl(225, 14%, 12%);
}
.tabs .tab:nth-of-type(1).active ~ .slider {
  left: 0;
}
.tabs .tab:nth-of-type(2).active ~ .slider {
  left: 33.33333%;
}
.tabs .tab:nth-of-type(3).active ~ .slider {
  left: 66.6666%;
}

Javascript

// prevent character input js

// Variables
const tabs = document.querySelectorAll('.tabs .tab');
const input = document.querySelector('.primary');
const myRegExInput = document.querySelector('.my-reg-ex');
const myRegExContainer = document.querySelector('.my-reg-ex-container');

// Regular Expressions

// digits only
let regex = /\d/;
// any character
let myRegEx = /./;

// Functions
// 1. Set active tab
const setActiveTab = (event) => {
  // sliding tabs functionality
  document.querySelector('.tab.active').classList.remove('active');
  event.currentTarget.classList.add('active');
  //

  // clear input
  input.value = '';

  if (event.currentTarget.classList.contains('digits')) {
    // allow digits only
    regex = /\d/;
    // hide custom regex input
    myRegExContainer.classList.remove('active');
  } else if (event.currentTarget.classList.contains('letters')) {
    // allow uppercase and lowercase letters only
    regex = /[A-Za-z]/;
    // hide custom regex input
    myRegExContainer.classList.remove('active');
  } else {
    // allow allow any character
    regex = myRegEx;
    // show custom regex input
    myRegExContainer.classList.add('active');
  }
};

// 2. Input filter
const inputFilter = (event, regEx) => {
  // catch pressed key's code
  // and convert it to an actual character
  let symbol = String.fromCharCode(event.keyCode);

  // if character doesn't belong to regEx set
  // then prevent it from being typed
  if (!regEx.test(symbol)) {
    event.preventDefault();
  }

// The test() method executes a search for a match between a regular expression and a specified string.
// Returns true if there is a match; false otherwise.
};

// 3. Input event
const inputEvent = (event) => {
  inputFilter(event, regex);
};

// 4. Setting user's input filter
const inputUserChoice = (event) => {
  // create and assign user's input to regEx
  myRegEx = new RegExp(`[${event.currentTarget.value}]`);
  regex = myRegEx;
};

// 5. Emptiness validation
const ifEmpty = (event) => {
  // custom regEx is empty
  // then allow any character
  if (
    !event.currentTarget.value.trim().length ||
    event.currentTarget.value === ''
  ) {
    regex = /./;
  }
};

// Event Listeners
// sliding tabs event
tabs.forEach((tab) => {
  tab.addEventListener('click', setActiveTab);
});
// input event
input.addEventListener('keypress', inputEvent);
// user's regEx
myRegExInput.addEventListener('input', inputUserChoice);
// check whether empty on blur
myRegExInput.addEventListener('blur', ifEmpty);

Allow vs Prevent character input

The difference is super minimal, it’s “!” (not) 😊

First off, we have to set a regular expression we need.

For example digits from 1 to 5.

const regex = /[1-5]/;

Then as I explained above we use:

regEx.test(string)

to test typed symbol against the regular expression.

To allow characters from regular expression set, code looks like this:

if (!regex.test(symbol)) {
      event.preventDefault();
}

// if symbol doesn't belong to a set, then prevent it

To prevent characters from regular expression set, code looks like this:

if (regex.test(symbol)) {
      event.preventDefault();
}

// if symbol belongs to a set, then prevent it

Frequently Asked Questions

// disallow characters in input

1️⃣ What is Keyboard Input Filter?

// disallow characters in input

A keyboard input filter in JavaScript is a function or set of functions that are used to intercept and modify user input as it is typed into a text field or other input element using a keyboard. The filter can be used to control what types of characters are allowed or disallowed, to convert input to a specific format, or to perform other types of input validation or manipulation.
Some common use cases for keyboard input filters include:
1️⃣ Allowing only certain types of characters, such as letters, numbers, or symbols, to be entered into an input field.

2️⃣ Enforcing a specific input format, such as a phone number with parentheses and dashes in specific locations.

3️⃣Limiting the length of input that can be entered into a field.

4️⃣Preventing users from entering certain words or phrases, such as profanity.

5️⃣ Converting input to a specific format, such as converting all characters to uppercase or lowercase.

2️⃣ What is Regular Expression in Javascript?

// disallow characters in input

A regular expression, also known as a regex or regexp, is a pattern that is used to match and manipulate text in JavaScript. It is a powerful tool that allows you to search for specific patterns within a string or replace certain parts of a string with other text.

Regular expressions are written using a combination of normal characters, special characters, and quantifiers.
For example, the regular expression /hello/ would match any string that contains the word “hello”.

Here are some common special characters used in regular expressions:
. (period): Matches any character except newline characters.

\d: Matches any digit (0-9).

\w: Matches any word character (a-z, A-Z, 0-9, and _).

\s: Matches any whitespace character (space, tab, newline).

^: Matches the beginning of a string.

$: Matches the end of a string.

[]: Matches any character within the brackets.

(): Groups a series of regular expressions together.

Note
If you have some Javascript project in mind that you want me to explain, please write it in the comments.
how to prevent character input in javascript
how to prevent character input in javascript

What to do next?

// keyboard input filter js

You can check out other cool Javascript tutorials here.

Resources

// keyboard input filter js

1️⃣ jssecrets.com

2️⃣ Good place to practice regular expressions: RegExr

3️⃣ Business illustrations by Storyset

4️⃣ Communication illustrations by Storyset

5️⃣ Work illustrations by Storyset

6️⃣ How to Prevent Character Input in Javascript Codepen

Ilyas Seisov

Ilyas Seisov

UI/Web designer and Javascript developer with Master's degree in Computer Science. He helps businesses transform ideas into reality with the power of design and code. Ilyas creates modern, aesthetic web applications and reads minds in a free time.

2 Comments

  1. Project: Keyboard Text Input Filtering prevent character input javascript

    In this CodePen user can choose set of characters that is allowed to type.

    Here, If i select the numbers and if i copy some alphabets and paste here it still allows me

    • Hi Nitesh 👋
      You are correct. Because the event listener is “keypress”.
      To accomplish what you are saying will require adding some additional code.

Leave a Reply

Your email address will not be published. Required fields are marked *