How to Prevent User to Enter Specific Key Using JavaScript

How to prevent user to enter specific key using Javascript

You can achieve that in a more simpler way like the following:

function onlyAlphabet(inputVal) {  var patt=/^[a-zA-Z]+$/;  if(patt.test(inputVal)){    document.getElementById('txtTravel').value = inputVal;  }  else{    var txt = inputVal.slice(0, -1);    document.getElementById('txtTravel').value = txt;  }  }
<div class="form-group">    <label class="form-text">Travels Name</label>    <input id="txtTravel" type="text" maxlength="50"     oninput="onlyAlphabet(value)" /> </div>

Disabling enter key for form

if you use jQuery, its quite simple. Here you go

if (event.which == '13') {

javascript : How to prevent user from entering = in textbox?

You could attach a listener to the input elements in the document, check if the user has pressed the = key, and if so, take an action.

Something like this should work:

const textInput = document.querySelector('input');textInput.addEventListener("keydown", function(event) {    if (event.keyCode === 187) {     console.log("equals pressed");        // Prevent default behaviour        event.preventDefault();        return false;    }});
<input type="text"></input>

Disable Enter key for whole form except one input inside it

I would use the keydown event because it is fired first.

You just have to add an additionnal comparison to check the tagName of the element where the event fired.

$('#formId').on('keydown', function(e) {
var keyCode = e.keyCode || e.which;
var tag =
if (keyCode === 13 && tag !=="TEXTAREA") {
console.log("Enter prevented")
return false;
console.log("Enter is ok...")
<script src=""></script>
<form id="formId">
<input type="text" value="ENTER does not work here"/><br>
<textArea>ENTER works here</textarea>

preventing user from entering certain characters while allowing others using jquery

$("input").on("input", function(){ $(this).val($(this).val().replace(/[^0-9]/g, ''));})
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Document</title> <script src=""></script></head><body> <input type="text"></body></html>

how to prevent user not to enter alphabets in input fied?

Based on the discussion, you can restrict alphabets from getting entered using the code of the key pressed.

Refer to the below code:-


  validateNumber(event) {
const keyCode = event.keyCode;

const excludedKeys = [8, 37, 39, 46];

if (!((keyCode >= 48 && keyCode <= 57) ||
(keyCode >= 96 && keyCode <= 105) ||
(excludedKeys.includes(keyCode)))) {


<input type="password" placeholder="Enter Mobile no" formControlName="mobile_no" (keydown)="validateNumber($event)">

You can refer to the stackblitz here.

Related Topics

Leave a reply