Monday, May 13, 2024
 Popular · Latest · Hot · Upcoming
12
rated 0 times [  13] [ 1]  / answers: 1 / hits: 22771  / 15 Years ago, tue, april 28, 2009, 12:00:00

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>

More From » regex

 Answers
51

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, '');
});

[#99636] Wednesday, April 22, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
declanm

Total Points: 614
Total Questions: 105
Total Answers: 97

Location: Dominica
Member since Sat, Nov 5, 2022
2 Years ago
declanm questions
Fri, Dec 18, 20, 00:00, 3 Years ago
Fri, Aug 7, 20, 00:00, 4 Years ago
Thu, Apr 2, 20, 00:00, 4 Years ago
;