Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Regex Only Textbox

I was able to find the solution for this in c# / .net but not for regular web html. If there's already an answer let me know and i'll close question.

How to create a text box that only will allow certain characters (ex. alphanumeric) based on a given regex (ex. [a-zA-Z0-9])? So if a user tries to enter anything else, paste included, it is removed or not allowed.

<input type="text" class="alphanumericOnly">
like image 885
SeanDowney Avatar asked Dec 17 '22 08:12

SeanDowney


1 Answers

The basic function would be this:

string = string.replace(/[^a-zA-Z0-9]/g, '')

This would replace any character that is not described by [a-zA-Z0-9].

Now you could either put it directly into your element declaration:

<input type="text" class="alphanumericOnly" onkeyup="this.value=this.value.replace(/[^a-zA-Z0-9]/g, '')">

Or (as you used the class hint) you assign this behavior to every input element with the class alphanumericOnly:

var inputElems = document.getElemenstByTagName("input");
for (var i=0; i<inputElems.length; i++) {
    var elem = inputElems[i];
    if (elem.nodeName == "INPUT" && /(?:^|\s+)alphanumericOnly(?:\s+|$)/.test(elem.className) {
        elem.onkeyup = function() {
            this.value = this.value.replace(/[^a-zA-Z0-9]/g, '');
        }
    }
}

But it’s probably easier to do that with jQuery or another JavaScript framework:

$("input.alphanumericOnly").bind("keyup", function(e) {
    this.value = this.value.replace(/[^a-zA-Z0-9]/g, '');
});
like image 162
Gumbo Avatar answered Dec 30 '22 07:12

Gumbo