Tuesday, May 3, 2011

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">
From stackoverflow
  • 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, '');
    });
    
  • Assuming you have the input stored as the variable input...

    input.onkeyup(function(e) {
      this.value = this.value.replace(/\W/g, '');
    }
    

    After every keypress the value of the input will be stripped of any non-alphanumeric characters.

0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.