svk
svk

Reputation: 4553

Allow text box only for letters using jQuery?

I want to make a text box allow only letters (a-z) using jQuery. Any examples?

Upvotes: 22

Views: 109333

Answers (12)

rybo111
rybo111

Reputation: 12588

Accepted answer

The accepted answer may be short, but has some drawbacks (see this fiddle):
  • The cursor moves to the end, no matter what key is pressed.
  • Non-letters are displayed momentarily, then disappear.
  • It is problematic on Chrome for Android (see my comment).

Alternative

The following creates an array of allowed key codes. If the key pressed is not in the array, then the input is ignored (see this fiddle):
$(".alpha-only").on("keydown", function(event){
  // Allow controls such as backspace, tab etc.
  var arr = [8,9,16,17,20,35,36,37,38,39,40,45,46];

  // Allow letters
  for(var i = 65; i <= 90; i++){
    arr.push(i);
  }
  
  // Prevent default if not in array
  if(jQuery.inArray(event.which, arr) === -1){
    event.preventDefault();
  }
});

Note that this allows uppercase and lowercase letters.

I have included key codes such as backspace, delete and arrow keys. You can create your own array using this list of key codes as a reference.

Modify on paste only

Of course, the user can still paste non-letters (such as via CTRL+V or right-click), so we still need to monitor all changes with .on("input"... but replace() only where necessary:

$(".alpha-only").on("input", function(){
  var regexp = /[^a-zA-Z]/g;
  if($(this).val().match(regexp)){
    $(this).val( $(this).val().replace(regexp,'') );
  }
});

This means we still have the undesired effect of the cursor jumping to the end, but only when the user pastes non-letters.

Avoiding autocorrect

Certain touchscreen keyboards will do everything in their power to autocorrect the user wherever it deems necessary. Surprisingly, this may even include inputs where `autocomplete` and `autocorrect` and even `spellcheck` are off.

To get around this, I would recommend using type="url", since URLs can accept upper and lower case letters but won't be auto-corrected. Then, to get around the browser trying to validate the URL, you must use novalidate in your form tag.

Upvotes: 27

Mayur Khairnar
Mayur Khairnar

Reputation: 25

if (!isValidName(name)) {           
   //return fail message
} else {
   //return success message
}

function isValidName(name) {
   var regex = new RegExp("^[a-zA-Z ]+$");
   if (regex.test(name)) {
     return true;  
   } else {
     return false; 
   }
}

Upvotes: 0

Mayur Khairnar
Mayur Khairnar

Reputation: 25

$("#txtName").keypress(function (e) {

    var key = e.keyCode;
    if ((key >= 48 && key <= 57) || (key >= 33 && key <= 47) || (key >= 58 && key <= 64) || (key >= 91 && key <= 96) || (key >= 123 && key <= 127)) {
        e.preventDefault();
    }
    var text = $(this).val();
    $(this).val(text.replace("  ", " "));

});  

Upvotes: 0

Rijo
Rijo

Reputation: 2718

Supports backspace:

new RegExp("^[a-zA-Z \b]*$");

This option will not check mobile. So you can use a jQuery Mask Plugin and use following code:

jQuery('.alpha-field, input[name=fname]').mask('Z',{translation:  {'Z': {pattern: /[a-zA-Z ]/, recursive: true}}});

Upvotes: 0

dn_pdih
dn_pdih

Reputation: 11

  $("#test").keypress(function(event){
        var inputValue = event.charCode;
        //alert(inputValue);
        if(!((inputValue > 64 && inputValue < 91) || (inputValue > 96 && inputValue < 123)||(inputValue==32) || (inputValue==0))){
            event.preventDefault();
        }
    });
  $("#test1").keypress(function(event){
        var inputValue = event.charCode;
        //alert(inputValue);
        if(!((inputValue > 47 && inputValue < 58) ||(inputValue==32) || (inputValue==0))){
            event.preventDefault();
        }
    });

  $("#test3").keypress(function(event){
        var inputValue = event.charCode;
        //alert(inputValue);
        if(!((inputValue > 64 && inputValue < 91) || (inputValue > 96 && inputValue < 123)||(inputValue==32)||(inputValue > 47 && inputValue < 58) ||(inputValue==32) || (inputValue==0))){
            event.preventDefault();
        }
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
For letters:<input type="text" id="test">   <br>
<br>
For Numbers: <input type="text" id="test1">
<br>
<br>
For Alphanumeric: <input type="text" id="test3">

Upvotes: 1

Vijay Lathiya
Vijay Lathiya

Reputation: 1227

// allow only  Alphabets A-Z a-z _ and space
$('.alphaonly').bind('keyup blur',function(){ 
    var node = $(this);
    node.val(node.val().replace(/[^A-Za-z_\s]/,'') ); }   // (/[^a-z]/g,''
);
// allow only  Number 0 to 9
$('.numberonly').bind('keyup blur',function(){ 
    var node = $(this);
    node.val(node.val().replace(/[^0-9]/,'') ); }   // (/[^a-z]/g,''
);

Upvotes: 4

Saurin Dashadia
Saurin Dashadia

Reputation: 1168

Solution described by @dev-null-dweller is working absolutely.

However, As of jQuery 3.0, .bind() method has been deprecated. It was superseded by the .on() method for attaching event handlers to a document since jQuery 1.7, so its use was already discouraged.

Check deprecated methods list for jQuery 3.0 here: http://api.jquery.com/category/deprecated/deprecated-3.0/

So the solution is to use .on() method instead .bind().

If you need to bind existing elements then the code will be :

$('.alphaonly').on('keyup blur', function(){
    var node = $(this);
    node.val( node.val().replace(/[^a-z]/g,'') ); 
}); 

If you need to bind to dynamic elements the code will be :

$(document).on('keyup blur', '.alphaonly', function(){
    var node = $(this);
    node.val(node.val().replace(/[^a-z]/g,'') );
});

You need to bind the event to document or some other element that already exist from the document load.

Hope this is helpful for new version of jQuery.

Upvotes: 1

Sachin Parse
Sachin Parse

Reputation: 1323

JQuery function to allow only small and Capital Letters:

Text Field:

<input id="a" type="text" />

JQuery Function:

$('#a').keydown(function (e) {
    if (e.ctrlKey || e.altKey) {
           e.preventDefault();
    } else {
           var key = e.keyCode;
           if (!((key == 8) || (key == 32) || (key == 46) || (key >= 35 && key <= 40) || (key >= 65 && key <= 90))) {
                e.preventDefault();
           }
    }
});

Upvotes: 0

Anjan Kant
Anjan Kant

Reputation: 4316

Demonstrated below to allow only letters [a-z] using Jquery:

  $(function() {
    $('#txtFirstName').keydown(function(e) {
      if (e.shiftKey || e.ctrlKey || e.altKey) {
        e.preventDefault();
      } else {
        var key = e.keyCode;
        if (!((key == 8) || (key == 32) || (key == 46) || (key >= 35 && key <= 40) || (key >= 65 && key <= 90))) {
          e.preventDefault();
        }
      }
    });
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<input id="txtFirstName" value="">

Upvotes: 3

Thanks to the first answer.. made this..

<input name="lorem" class="alpha-only">

<script type="text/javascript">
   $(function() 
   {
        $('.alpha-only').bind('keyup input',function()
        {       
            if (this.value.match(/[^a-zA-Z áéíóúÁÉÍÓÚüÜ]/g)) 
            {
                this.value = this.value.replace(/[^a-zA-Z áéíóúÁÉÍÓÚüÜ]/g, '');
            }
        });
    });
</script>

This has some improvements like letters with accents, and changing "blur" for "input" corrects the Non-letters displayed momentarily, also when you select text with the mouse and dragging is corrected..

Upvotes: 0

dev-null-dweller
dev-null-dweller

Reputation: 29462

<input name="lorem" onkeyup="this.value=this.value.replace(/[^a-z]/g,'');">

And can be the same to onblur for evil user who like to paste instead of typing ;)

[+] Pretty jQuery code:

<input name="lorem" class="alphaonly">
<script type="text/javascript">
$('.alphaonly').bind('keyup blur',function(){ 
    var node = $(this);
    node.val(node.val().replace(/[^a-z]/g,'') ); }
);
</script>

Upvotes: 53

Anurag
Anurag

Reputation: 141879

To allow only lower case alphabets, call preventDefault on the event object if the key code is not in the range 'a'..'z'. Check between 65..90 or 'A'..'Z' too if upper case should be allowed.

Or, alternatively use one of the many input mask plugins out there.

See example.

​$(<selector>).keypress(function(e) {
    if(e.which < 97 /* a */ || e.which > 122 /* z */) {
        e.preventDefault();
    }
});​​​​​

Upvotes: 7

Related Questions