Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limit characters to Letters and Numbers in input field

Tags:

regex

forms

input

I want that people trying to subscribe on my website to enter a nickname and that nickname should exclusively consist of letters and numbers (no special characters at all).

I would like somthing as following : abcdefghijklmnopqrstuvwxyz1234567890 only.

How can I check if it has only those?

like image 640
james Avatar asked Jul 20 '11 13:07

james


1 Answers

The HTML5 solution would be...

<input type="text" id="input-nickname" name="nickname" pattern="[a-z\d]*"  />

jsFiddle.

However, for best browser support, you could use JavaScript...

document.getElementById('input-nickname').onkeyup = function(event) {

    this.value = this.value.replace(/[^a-z\d]/, '');

}

jsFiddle.

To make the JavaScript version similar to the HTML5 method, look at the form's submit event.

Keep in mind this has a pretty strict definition of letters and numbers. For proper Unicode support, find the ranges you care about and use \u0000-\uFFFF to specify it.

like image 51
alex Avatar answered Oct 18 '22 19:10

alex