开发者

Limit characters to Letters and Numbers in input field

I want that people trying to subscribe on my website to enter a nickname and that nicknam开发者_开发知识库e 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?


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.


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.


Here is my simple solution for React users only (the above solution doesn't work properly in React). 3 steps.

First, create a state.

const [tagInputVal, setTagInputVal] = useState("");

Then, use the state as input value (value={tagInputVal}) and pass the event to the onChange handler.

<input id="tag-input" type="text" placeholder="Add a tag" value={tagInputVal} onChange={(e) => onChangeTagInput(e)}></input>

Then, set the value of the event inside onChange handler.

function onChangeTagInput(e) {
    setTagInputVal(e.target.value.replace(/[^a-zA-Z\d]/ig, ""));
}


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/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜