4

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">
3
  • Have you even tried to find a solution that already exists on the web? I am sure they are out there, and I don't really want to be your typist, so go Google it and when you have a question about particulars, come back here - unless you want to pay me to write code for you. Commented Apr 28, 2009 at 20:31
  • 1
    Here you go: xploredotnet.com/2007/09/… Commented Apr 28, 2009 at 20:35
  • 1
    Right, I could have done that, however using SO for answers also has the possibility to generate discussion, new ideas etc, rather than just a static site. Thanks for your help though Commented Apr 28, 2009 at 21:01

5 Answers 5

9

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, '');
});
Sign up to request clarification or add additional context in comments.

Comments

3
  1. Example on how to allow alphanumeric chars and space (a-z, A-Z, 0-9 and space, others are eliminated as typed):
$('#some_input_field_id').unbind('change keyup paste mouseup').bind('change keyup paste mouseup', function(){if(this.value.match(/[^a-zA-Z0-9 ]/g)){this.value = this.value.replace(/[^a-zA-Z0-9 ]/g, '');}});
  1. Example on how to allow only lowercase alpha chars (a-z, others are eliminated as typed):
$('#some_input_field_id').unbind('change keyup paste mouseup').bind('change keyup paste mouseup', function(){if(this.value.match(/[^a-z]/g)){this.value = this.value.replace(/[^a-z]/g, '');}});

Etc...

EDIT: As of jQuery version 3.0, .bind() and .unbind() are deprecated. Instead, if you use jQuery 3.0 (and above), simply use .on() and .off() event handler attachments, respectively.

Comments

0

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.

Comments

0

If you use a .replace method on the keyup event the input will flicker with the non-alphanumeric characters as they're typed, which appears sloppy and doesn't comply with OCD folks like myself.

A cleaner approach would be to bind to the keypress event and deny the characters before they even arrive at the input, like the following:

$('.alphanumericOnly').keypress(function(e){
    var key = e.which;
    return ((key >= 48 && key <= 57) || (key >= 65 && key <= 90) || (key >= 95 && key <= 122));
});

A list of basic keycodes can be found here if this particular set doesn't suit your specific needs.

Comments

0

I've noticed that at least in my case, with the paste and drop events, replacing the text wasn't working because at that point the value property of the input was still the previous one. So I did this:

With pure javascript:

function filterInputs() {
  var that = this;
  setTimeout(function() {
    that.value = that.value.replace(/[^a-zA-Z0-9]/g, '');
  }, 0);
}

var input = document.getElementById('theInput');

input.addEventListener('keyup', filterInputs);
input.addEventListener('paste', filterInputs);
input.addEventListener('drop', filterInputs);
input.addEventListener('change', filterInputs);
Try writing non-alphanumeric characters: <input type="text" id="theInput">
<br>You can use this input to write anything and copy-paste/drag & drop it into the other one: <input type="text">

With jQuery:

function filterInputs() {
  var that = this;
  setTimeout(function() {
    that.value = that.value.replace(/[^a-zA-Z0-9]/g, '');
  }, 0);
}

$('#theInput').on('keyup paste drop change', filterInputs);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Try writing non-alphanumeric characters: <input type="text" id="theInput">
<br>You can use this input to write anything and copy-paste/drag & drop it into the other one: <input type="text">

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.