Limit characters to Letters and Numbers in input f

2019-04-08 18:36发布

问题:

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?

回答1:

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.



回答2:

I suggest to have a look at: RegEx library

It contains a lot of RegEx that you can test directly on the site and change according to your needs.

I always use it as source whenever I need to work with RegEx.



回答3:

with javasacript

function testAlphanumeric(input){
var regex=/^[0-9A-Za-z]+$/;
if(regex.test(input)){
alert("Good")
return true;
} else {
alert("Incorrect")
return false;
}
}

source link: http://newsourcemedia.com/blog/javascript-non-alphanumeric-characters-regex/