S.Pearson
S.Pearson

Reputation: 123

Restrict input to specific characters

I'd like to restrict an input field to any letter, a period and a hyphen.

I thought the following would allow the input of any letter but it's not allowing anything to be inputted. It's probably something obvious that I'm overlooking.

$('input').on('keypress', function(event){
    if (event.keyCode > 65 || event.keyCode < 90)
        return false;
});

Thanks in advance!

Upvotes: 2

Views: 1491

Answers (2)

JSK
JSK

Reputation: 583

If you want to use the numbers only then try this:

$('#text').keypress(function (e) {
var regex = new RegExp("^[a-zA-Z]\-.+$");
var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
if (regex.test(str)) {
    return true;
}

e.preventDefault();
return false;
});

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337560

To achieve this you can use a Regular Expression to compare the entered text to the values you want to allow and remove any you do not. You should also use the keyup event when checking the value. You can also use the input, blur and paste events to make sure all events are covered for all browsers. Try this:

$('input').on('input blur keyup paste', function() {
  $(this).val(function(i, v) {
    return v.replace(/[^a-z\.-]/ig, '');
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="foo" type="text" /> 

Upvotes: 3

Related Questions