How to force input to only allow Alpha Letters?
Asked Answered
I

12

40

using jQuery here, however unable to prevent numbers from being typed into the input field

http://codepen.io/leongaban/pen/owbjg

Input

<input type="text" name="field" maxlength="8"
    title="Only Letters"
    value="Type Letters Only"
    onkeydown="return alphaOnly(event);"
    onblur="if (this.value == '') {this.value = 'Type Letters Only';}"
    onfocus="if (this.value == 'Type Letters Only') {this.value = '';}"/>

jQuery

function alphaOnly(event) {

  alert(event);

  var key;

  if (window.event) {
    key = window.event.key;
  } else if (e) {
    key = e.which;
  }
  //var key = window.event.key || event.key;
  alert(key.value);
  return ((key >= 65 && key <= 90) || (key >= 95 && key <= 122));

}

I've seen plenty of examples here on how to restrict to only Numbers, and I'm using the correct key codes for a-z and A-Z. Do you see what I'm doing wrong?

Inboard answered 22/10, 2013 at 2:49 Comment(7)
Limiting input is not user friendly, you only care what the value is when you go to use it (say when a form is submitted). Let the user arrive at a suitable value however they want, especially as they do not need to use the keyboard to enter a value in an input.Tarantass
How about calling preventDefault on the event object if key code is not in the range A-Za-zGiorgia
e.preventDefault stopped my input from taking in any characters :( @Tarantass no numbers are allowed in my input to be typed howeverInboard
Responding to key presses and stopping anything other than letters doesn't stop copy/paste (by any one of at least 3 methods), drag and drop or even script to insert any value the user wants.Tarantass
Oh good to know thanks :) I don't believe the users I target would use drag and drop or a script, but hmm copy paste...Inboard
Always remember that users DO the silly thing someday. Never hope they won'tPulpiteer
How about the html "pattern" attribute? <input type="text" pattern="[a-zA-Z]">Legibility
J
23

The property event.key gave me an undefined value. Instead, I used event.keyCode:

function alphaOnly(event) {
  var key = event.keyCode;
  return ((key >= 65 && key <= 90) || key == 8);
};

Note that the value of 8 is for the backspace key.

Johnathon answered 22/10, 2013 at 3:3 Comment(3)
Thanks so much! I just also found the answer here:#13119624 but was trying to figure out the delete key :DInboard
this doesn't allow space. how to allow space with that codes?Cysteine
To allow space: function alphaOnly(event) { var key = event.keyCode; return ((key >= 65 && key <= 90) || key == 8 || key==32); }Resale
M
97

Short ONELINER:

<input onkeydown="return /[a-z]/i.test(event.key)" >

For all unicode letters try this regexp: /\p{L}/u (but ... this) - and here is working example :)

Misdemeanor answered 6/9, 2018 at 11:48 Comment(4)
How would I add a hyphen(-) to the allowed input here?Edentate
@Edentate change [a-z] to [a-z\-]Ary
Not sure if I should actually post a new question for this but for numerical only this would be <input onkeydown="return /[0-9]/i.test(event.key)" > right?Edentate
+1'd this but I do think you could do with explaining what is going on in it. E.g. /i means case sensitive in "/[a-z]/i" and .test() checks the regex - otherwise people will just slap this in without understanding it.Theta
J
23

The property event.key gave me an undefined value. Instead, I used event.keyCode:

function alphaOnly(event) {
  var key = event.keyCode;
  return ((key >= 65 && key <= 90) || key == 8);
};

Note that the value of 8 is for the backspace key.

Johnathon answered 22/10, 2013 at 3:3 Comment(3)
Thanks so much! I just also found the answer here:#13119624 but was trying to figure out the delete key :DInboard
this doesn't allow space. how to allow space with that codes?Cysteine
To allow space: function alphaOnly(event) { var key = event.keyCode; return ((key >= 65 && key <= 90) || key == 8 || key==32); }Resale
S
12

Rather than relying on key codes, which can be quite cumbersome, you can instead use regular expressions. By changing the pattern we can easily restrict the input to fit our needs. Note that this works with the keypress event and will allow the use of backspace (as in the accepted answer). It will not prevent users from pasting 'illegal' chars.

function testInput(event) {
   var value = String.fromCharCode(event.which);
   var pattern = new RegExp(/[a-zåäö ]/i);
   return pattern.test(value);
}

$('#my-field').bind('keypress', testInput);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>
   Test input:
   <input id="my-field" type="text">
</label>
Scouring answered 3/8, 2016 at 8:42 Comment(2)
Hi bro can you provide a code for number only like this box?Oviparous
In order to modify the input allowed, simply modify the regular expression to your liking. For example, the regular expression for representing a positive integer could be stated as /[0-9]+/. But maybe you have something more specific in mind when you say number?Scouring
H
9

On newer browsers, you can use:

<input type="text" name="country_code" 
    pattern="[A-Za-z]" title="Three letter country code">

You can use regular expressions to restrict the input fields.

Hanahanae answered 26/5, 2016 at 4:12 Comment(3)
Can you add a jsfiddle for this? I can't seem to get it to workAntebi
^ my mistake. I see that it responds when combined with a submit button, but does not prevent the key entry in real time as per w3schools.com/tags/att_input_pattern.aspAntebi
Notice that this will work if you enter ONE letter only. So if you want as many letters as you want then add + (See example below) pattern="[A-Za-z]+"Head
J
7

Nice one-liner HTML only:

 <input type="text" id='nameInput' onkeypress='return ((event.charCode >= 65 && event.charCode <= 90) || (event.charCode >= 97 && event.charCode <= 122) || (event.charCode == 32))'>
Jenness answered 31/1, 2018 at 6:8 Comment(0)
T
4

A lot of the other solutions that use keypress will not work on mobile, you need to use input.

html

<input type="text" id="name"  data-value="" autocomplete="off" spellcheck="true" placeholder="Type your name" autofocus />

jQuery

$('#name').on('input', function() {
    var cursor_pos = $(this).getCursorPosition()
    if(!(/^[a-zA-Z ']*$/.test($(this).val())) ) {
        $(this).val($(this).attr('data-value'))
        $(this).setCursorPosition(cursor_pos - 1)
        return
    }
    $(this).attr('data-value', $(this).val())
})

$.fn.getCursorPosition = function() {
    if(this.length == 0) return -1
    return $(this).getSelectionStart()
}
$.fn.setCursorPosition = function(position) {
    if(this.lengh == 0) return this
    return $(this).setSelection(position, position)
}
$.fn.getSelectionStart = function(){
  if(this.lengh == 0) return -1
  input = this[0]
  var pos = input.value.length
  if (input.createTextRange) {
    var r = document.selection.createRange().duplicate()
    r.moveEnd('character', input.value.length)
    if (r.text == '') 
    pos = input.value.length
    pos = input.value.lastIndexOf(r.text)
  } else if(typeof(input.selectionStart)!="undefined")
  pos = input.selectionStart
  return pos
}
$.fn.setSelection = function(selectionStart, selectionEnd) {
  if(this.lengh == 0) return this
  input = this[0]
  if(input.createTextRange) {
    var range = input.createTextRange()
    range.collapse(true)
    range.moveEnd('character', selectionEnd)
    range.moveStart('character', selectionStart)
    range.select()
  }
  else if (input.setSelectionRange) {
    input.focus()
    input.setSelectionRange(selectionStart, selectionEnd)
  }
  return this
}
Tetrapod answered 30/8, 2019 at 1:29 Comment(0)
P
3
<input type="text" name="field" maxlength="8"
    onkeypress="return onlyAlphabets(event,this);" />

function onlyAlphabets(e, t) {
            try {
                if (window.event) {
                    var charCode = window.event.keyCode;
                }
                else if (e) {
                    var charCode = e.which;
                }
                else { return true; }
                if ((charCode > 64 && charCode < 91) || (charCode > 96 && charCode < 123))
                    return true;
                else
                    return false;
            }
            catch (err) {
                alert(err.Description);
            }
        }
Premundane answered 6/4, 2016 at 12:17 Comment(0)
S
3

You can do something like this assuming that you have more than one input :

    


    function alphaOnly() {
    let nameInput = document.querySelectorAll('.js-name');
      nameInput.forEach((input) => {
  
        input.addEventListener('keydown', (e) => {
          let charCode = e.keyCode;
  
          if ((charCode >= 65 && charCode <= 90) || charCode == 8 || charCode == 32) {
            null;
          } else {
            e.preventDefault();
          }
        });
      });
    }

alphaOnly();
First name: <input type="text" class="js-name" name="fname"><br>
Last name: <input type="text" class="js-name" name="lname"><br>

This allows you to use blank and backspace -> (charCode == 8 || charCode == 32). If you don2t need it you can remove this conditon.

Shick answered 22/3, 2022 at 11:50 Comment(0)
H
2

keypress, keyup and keydown events are not works in mobile devices. And KeyboardEvent.keyCode is no longer recommended. So I found a new way with input event and RegExp. It will works fine for all kind of devices.

const alphaOnlyInput = document.getElementById('alpha-only-input'),
  alphaOnlyPattern = new RegExp('^[a-zA-Z ]+$')

let previousValue = ''

alphaOnlyInput.addEventListener('input', (e) => {
  let currentValue = alphaOnlyInput.value

  if (e.inputType.includes('delete') || alphaOnlyPattern.test(currentValue)) {
    previousValue = currentValue
  }

  alphaOnlyInput.value = previousValue
})
<label>Alpha Only: </label>
<input type="text" id="alpha-only-input" name="alphaOnly">
Hecklau answered 2/7, 2021 at 12:46 Comment(0)
N
0
<input type="text" name="name" id="event" onkeydown="return alphaOnly(event);"   required />


function alphaOnly(event) {
  var key = event.keyCode;`enter code here`
  return ((key >= 65 && key <= 90) || key == 8);
};
Nippers answered 15/11, 2017 at 10:12 Comment(0)
A
0

You can subscribe to "InputEvent" and then get "data" prop. For example

input.addEventListener('beforeinput', (event) => {
    const data = event.data;

    // if "data" is present - user enter some character
    // if "data" is NOT present - user tap non character key (e.g. delete, shift and other)
    if(data) {
        // check if data is not number
        const isAllow = /\D/.test(data);

        if(!isAllow) {
            e.preventDefault();
        }
    }
})

More info

  1. event.data - https://developer.mozilla.org/en-US/docs/Web/API/InputEvent/data
  2. beforeinput event - https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/beforeinput_event
Attainture answered 13/8, 2021 at 14:38 Comment(0)
C
-1

If your form is PHP based, it would work this way within your " <?php $data = array(" code:

    'onkeypress' => 'return /[a-z 0-9]/i.test(event.key)', 
Credence answered 31/8, 2020 at 11:38 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.