Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent user to enter specific key using Javascript

I have a text field and I want to allow only alphabet. So I write the below Javascript method to prevent other keys. Unfortunately my text field is allowing uparrow(^). Can any one tell me how to restrict uparrow(^) ?

function onlyAlphabet(evt) {
    var theEvent = evt || window.event;
    var key = theEvent.keyCode || theEvent.which;

    var keychar = String.fromCharCode(key);
    var keycheck = /[a-zA-z\s]/;

    if (!(key == 8 || key == 27 || key == 46 || key == 9 || key == 39)) // backspace delete  escape arrows
    {
        if (!keycheck.test(keychar)) {
            theEvent.returnValue = false;//for IE
            if (theEvent.preventDefault)
                theEvent.preventDefault();//Firefox
        }
    }
}

html code

<div class="form-group">
   <label class="form-text">Travels Name</label>
   <h:inputText value="#{bean.travelName}" maxlength="50" onkeypress="return onlyAlphabet(event)" />
</div>
like image 478
Mihir Avatar asked Aug 11 '26 02:08

Mihir


1 Answers

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>
like image 126
Mamun Avatar answered Aug 13 '26 17:08

Mamun