Best way to alphanumeric check in Javascript
Can you please suggest the best possible way to perform an alpha numeric check on an INPUT field in JSP? I have attached my current code and I know its no where close to perfect :)
<script type="text/javascript">
function validateCode(){
var TCode = document.getElementById('TCode').value;
for(var i=0; i<TCode.length; i++)
{
var char1 = TCode.charAt(i);
var cc = char1.charCodeAt(0);
if((cc>47 && cc<58) || (cc>64 && cc<91) || (cc>96 && cc<123))
{
}
else {
alert('Input is not alphanumeric');
return false;
}
}
return true;
}
javascript validation
add a comment |
Can you please suggest the best possible way to perform an alpha numeric check on an INPUT field in JSP? I have attached my current code and I know its no where close to perfect :)
<script type="text/javascript">
function validateCode(){
var TCode = document.getElementById('TCode').value;
for(var i=0; i<TCode.length; i++)
{
var char1 = TCode.charAt(i);
var cc = char1.charCodeAt(0);
if((cc>47 && cc<58) || (cc>64 && cc<91) || (cc>96 && cc<123))
{
}
else {
alert('Input is not alphanumeric');
return false;
}
}
return true;
}
javascript validation
1
Depends how you define "best". Most of the answers below suggest regex, which performs much slower than your original code. I've cleaned up your code a bit, which actually performs very well.
– Michael Martin-Smucker
Aug 17 '14 at 18:31
add a comment |
Can you please suggest the best possible way to perform an alpha numeric check on an INPUT field in JSP? I have attached my current code and I know its no where close to perfect :)
<script type="text/javascript">
function validateCode(){
var TCode = document.getElementById('TCode').value;
for(var i=0; i<TCode.length; i++)
{
var char1 = TCode.charAt(i);
var cc = char1.charCodeAt(0);
if((cc>47 && cc<58) || (cc>64 && cc<91) || (cc>96 && cc<123))
{
}
else {
alert('Input is not alphanumeric');
return false;
}
}
return true;
}
javascript validation
Can you please suggest the best possible way to perform an alpha numeric check on an INPUT field in JSP? I have attached my current code and I know its no where close to perfect :)
<script type="text/javascript">
function validateCode(){
var TCode = document.getElementById('TCode').value;
for(var i=0; i<TCode.length; i++)
{
var char1 = TCode.charAt(i);
var cc = char1.charCodeAt(0);
if((cc>47 && cc<58) || (cc>64 && cc<91) || (cc>96 && cc<123))
{
}
else {
alert('Input is not alphanumeric');
return false;
}
}
return true;
}
javascript validation
javascript validation
asked Dec 13 '10 at 22:23
t0mcatt0mcat
1,928183854
1,928183854
1
Depends how you define "best". Most of the answers below suggest regex, which performs much slower than your original code. I've cleaned up your code a bit, which actually performs very well.
– Michael Martin-Smucker
Aug 17 '14 at 18:31
add a comment |
1
Depends how you define "best". Most of the answers below suggest regex, which performs much slower than your original code. I've cleaned up your code a bit, which actually performs very well.
– Michael Martin-Smucker
Aug 17 '14 at 18:31
1
1
Depends how you define "best". Most of the answers below suggest regex, which performs much slower than your original code. I've cleaned up your code a bit, which actually performs very well.
– Michael Martin-Smucker
Aug 17 '14 at 18:31
Depends how you define "best". Most of the answers below suggest regex, which performs much slower than your original code. I've cleaned up your code a bit, which actually performs very well.
– Michael Martin-Smucker
Aug 17 '14 at 18:31
add a comment |
7 Answers
7
active
oldest
votes
You can use this regex /^[a-z0-9]+$/i
3
of course this assumes that that the empty string ("") should not be matched.
– zzzzBov
Dec 13 '10 at 22:28
11
ñdoes not fall into the pattern however fully valid UTF-8 char.
– Oybek
Apr 4 '13 at 16:35
7
/^[a-z0-9]+$/i.test( TCode )
– Alex V
Oct 14 '13 at 18:12
3
Testing a regular expression seems to be much slower (66% in Chrome 36) thancharCodeAt(). See jsPerf and my answer below.
– Michael Martin-Smucker
Aug 17 '14 at 18:29
1
This regex does not work with special character letters used in some languages, like "ą", "ź", "ć" etc.
– Rafał Swacha
Jan 15 '16 at 12:01
|
show 5 more comments
The asker's original inclination to use str.charCodeAt(i) appears to be faster than the regular expression alternative. In my test on jsPerf the RegExp option performs 66% slower in Chrome 36 (and slightly slower in Firefox 31).
Here's a cleaned-up version of the original validation code that receives a string and returns true or false:
function isAlphaNumeric(str) {
var code, i, len;
for (i = 0, len = str.length; i < len; i++) {
code = str.charCodeAt(i);
if (!(code > 47 && code < 58) && // numeric (0-9)
!(code > 64 && code < 91) && // upper alpha (A-Z)
!(code > 96 && code < 123)) { // lower alpha (a-z)
return false;
}
}
return true;
};
Of course, there may be other considerations, such as readability. A one-line regular expression is definitely prettier to look at. But if you're strictly concerned with speed, you may want to consider this alternative.
12
Programmers love the look of code, but you see its inner beauty.
– Ziggy
Sep 16 '14 at 3:14
Interesting alternative approach - never even crossed my mind. I came here with only regex in mind!
– ozzy432836
Oct 10 '18 at 13:01
The answer that makes you think and makes you understand what it means "programming". I use your way of thinking, in my answer
– Oscar Zarrus
Nov 20 '18 at 1:16
add a comment |
You don't need to do it one at a time. Just do a test for any that are not alpha-numeric. If one is found, the validation fails.
function validateCode(){
var TCode = document.getElementById('TCode').value;
if( /[^a-zA-Z0-9]/.test( TCode ) ) {
alert('Input is not alphanumeric');
return false;
}
return true;
}
If there's at least one match of a non alpha numeric, it will return false.
add a comment |
Check it with a regex.
Javascript regexen don't have POSIX character classes, so you have to write character ranges manually:
if (!input_string.match(/^[0-9a-z]+$/))
show_error_or_something()
Here ^ means beginning of string and $ means end of string, and [0-9a-z]+ means one or more of character from 0 to 9 OR from a to z.
More information on Javascript regexen here:
https://developer.mozilla.org/en/JavaScript/Guide/Regular_Expressions
12
+1 for explaining the basic regex and linking to a guide, rather than giving the user a "magic string".
– Charles Burns
Apr 29 '13 at 16:46
5
you need to add A-Z
– inor
Jul 23 '14 at 4:56
1
@inor you can just add 'i' at the end of the regex to specify case insensitivity, .i.e./^[a-z0-9]+$/iand this will cover both lower and upper case letters
– LJH
Jul 26 '18 at 17:50
add a comment |
// On keypress event call the following method
function AlphaNumCheck(e) {
var charCode = (e.which) ? e.which : e.keyCode;
if (charCode == 8) return true;
var keynum;
var keychar;
var charcheck = /[a-zA-Z0-9]/;
if (window.event) // IE
{
keynum = e.keyCode;
}
else {
if (e.which) // Netscape/Firefox/Opera
{
keynum = e.which;
}
else return true;
}
keychar = String.fromCharCode(keynum);
return charcheck.test(keychar);
}
Further, this article also helps to understand JavaScript alphanumeric validation.
add a comment |
I would create a String prototype method:
String.prototype.isAlphaNumeric = function() {
var regExp = /^[A-Za-z0-9]+$/;
return (this.match(regExp));
};
Then, the usage would be:
var TCode = document.getElementById('TCode').value;
return TCode.isAlphaNumeric()
3
Maintainable JavaScript: Don’t modify objects you don’t own
– SeinopSys
Apr 28 '15 at 9:54
2
DJDavid98: I don't think that the rule "don't modify objects you don't own" applies here. Justin was just extending the capabilities of String, not modifying existing functionalities. For perspective, in C# world, that would be considered as a perfectly valid usage of an extension method. Even if some day "String.isAlphaNumeric(): boolean" would be implemented by browser manufacturers, neither the signature nor action would actualy change, so I can't see any reductions of maintainability in this particular example. That something is a rule doesn't imply that there are no exceptions.
– Risto Välimäki
Jun 8 '15 at 6:38
add a comment |
Excuse me all, no controversy. But for the community to grow as it has grown me in these years, it is good to make some notes.
The real alphanumeric string is like "0a0a0a0b0c0d" and not like "000000" or "qwertyuio".
All the answers I read here, returned true in both cases. And forgive me, IMHO, this is not right.
If I want to check if my "00000" string is alphanum, my "human" answer is unquestionably FALSE.
Why? Simple. I cannot find any letter char. So, is a simple numeric string [0-9].
On the other hand, if I wanted to check my "abcdefg" string, my "human" answer is even FALSE. I don't see numbers, so it's not alphanumeric. Just alpha [a-zA-Z].
The Michael Martin-Smucker's answer has been illuminating.
However he was aimed at achieving better performance instead of regex. This is true, using a low level way there's a better perfomance. But results it's the same.
The strings "0123456789" (only numeric), "qwertyuiop" (only alpha) and "0a1b2c3d4f4g" (alphanumeric) returns TRUE as alphanumeric. Same regex /^[a-z0-9]+$/i way.
The reason why the regex does not work is as simple as obvious. The syntax indicates or, not and.
So, if is it only numeric or if is it only letters, regex returns true.
But, the Michael Martin-Smucker's answer was nevertheless illuminating. For me.
It allowed me to think at "low level", to create a real function that unambiguous
processes an alphanumeric string. I called it like PHP relative function ctype_alnum.
Here's the code:
function ctype_alnum(str) {
var code, i, len;
var isNumeric = false, isAlpha = false; //I assume that it is all non-alphanumeric
for (i = 0, len = str.length; i < len; i++) {
code = str.charCodeAt(i);
switch (true){
case code > 47 && code < 58: // check if 0-9
isNumeric = true;
break;
case (code > 64 && code < 91) || (code > 96 && code < 123): //check if A-Z or a-z
isAlpha = true;
break;
default: // not 0-9, not A-Z or a-z
return false; //stop function with false result, no more checks
}
}
return isNumeric && isAlpha; //return the loop results, if both are true, the string is certainly alphanumeric
};
... and here's the DEMO
I came to this discussion because I was looking for an alternative in javascript to the PHP function. I didn't find the answer "ready-to-go", but as often happens on Stackoverflow, the concept of knowledge and comparison with each other is something sublime, that leads you to think about someone's answer and find together the solution you were looking for, but you didn't think you knew it.
And share it!
Best
Oscar
add a comment |
protected by Robert Harvey♦ Dec 29 '11 at 5:21
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?
7 Answers
7
active
oldest
votes
7 Answers
7
active
oldest
votes
active
oldest
votes
active
oldest
votes
You can use this regex /^[a-z0-9]+$/i
3
of course this assumes that that the empty string ("") should not be matched.
– zzzzBov
Dec 13 '10 at 22:28
11
ñdoes not fall into the pattern however fully valid UTF-8 char.
– Oybek
Apr 4 '13 at 16:35
7
/^[a-z0-9]+$/i.test( TCode )
– Alex V
Oct 14 '13 at 18:12
3
Testing a regular expression seems to be much slower (66% in Chrome 36) thancharCodeAt(). See jsPerf and my answer below.
– Michael Martin-Smucker
Aug 17 '14 at 18:29
1
This regex does not work with special character letters used in some languages, like "ą", "ź", "ć" etc.
– Rafał Swacha
Jan 15 '16 at 12:01
|
show 5 more comments
You can use this regex /^[a-z0-9]+$/i
3
of course this assumes that that the empty string ("") should not be matched.
– zzzzBov
Dec 13 '10 at 22:28
11
ñdoes not fall into the pattern however fully valid UTF-8 char.
– Oybek
Apr 4 '13 at 16:35
7
/^[a-z0-9]+$/i.test( TCode )
– Alex V
Oct 14 '13 at 18:12
3
Testing a regular expression seems to be much slower (66% in Chrome 36) thancharCodeAt(). See jsPerf and my answer below.
– Michael Martin-Smucker
Aug 17 '14 at 18:29
1
This regex does not work with special character letters used in some languages, like "ą", "ź", "ć" etc.
– Rafał Swacha
Jan 15 '16 at 12:01
|
show 5 more comments
You can use this regex /^[a-z0-9]+$/i
You can use this regex /^[a-z0-9]+$/i
edited May 23 '17 at 12:18
Community♦
11
11
answered Dec 13 '10 at 22:26
Mahesh VelagaMahesh Velaga
16.9k43155
16.9k43155
3
of course this assumes that that the empty string ("") should not be matched.
– zzzzBov
Dec 13 '10 at 22:28
11
ñdoes not fall into the pattern however fully valid UTF-8 char.
– Oybek
Apr 4 '13 at 16:35
7
/^[a-z0-9]+$/i.test( TCode )
– Alex V
Oct 14 '13 at 18:12
3
Testing a regular expression seems to be much slower (66% in Chrome 36) thancharCodeAt(). See jsPerf and my answer below.
– Michael Martin-Smucker
Aug 17 '14 at 18:29
1
This regex does not work with special character letters used in some languages, like "ą", "ź", "ć" etc.
– Rafał Swacha
Jan 15 '16 at 12:01
|
show 5 more comments
3
of course this assumes that that the empty string ("") should not be matched.
– zzzzBov
Dec 13 '10 at 22:28
11
ñdoes not fall into the pattern however fully valid UTF-8 char.
– Oybek
Apr 4 '13 at 16:35
7
/^[a-z0-9]+$/i.test( TCode )
– Alex V
Oct 14 '13 at 18:12
3
Testing a regular expression seems to be much slower (66% in Chrome 36) thancharCodeAt(). See jsPerf and my answer below.
– Michael Martin-Smucker
Aug 17 '14 at 18:29
1
This regex does not work with special character letters used in some languages, like "ą", "ź", "ć" etc.
– Rafał Swacha
Jan 15 '16 at 12:01
3
3
of course this assumes that that the empty string (
"") should not be matched.– zzzzBov
Dec 13 '10 at 22:28
of course this assumes that that the empty string (
"") should not be matched.– zzzzBov
Dec 13 '10 at 22:28
11
11
ñ does not fall into the pattern however fully valid UTF-8 char.– Oybek
Apr 4 '13 at 16:35
ñ does not fall into the pattern however fully valid UTF-8 char.– Oybek
Apr 4 '13 at 16:35
7
7
/^[a-z0-9]+$/i.test( TCode )
– Alex V
Oct 14 '13 at 18:12
/^[a-z0-9]+$/i.test( TCode )
– Alex V
Oct 14 '13 at 18:12
3
3
Testing a regular expression seems to be much slower (66% in Chrome 36) than
charCodeAt(). See jsPerf and my answer below.– Michael Martin-Smucker
Aug 17 '14 at 18:29
Testing a regular expression seems to be much slower (66% in Chrome 36) than
charCodeAt(). See jsPerf and my answer below.– Michael Martin-Smucker
Aug 17 '14 at 18:29
1
1
This regex does not work with special character letters used in some languages, like "ą", "ź", "ć" etc.
– Rafał Swacha
Jan 15 '16 at 12:01
This regex does not work with special character letters used in some languages, like "ą", "ź", "ć" etc.
– Rafał Swacha
Jan 15 '16 at 12:01
|
show 5 more comments
The asker's original inclination to use str.charCodeAt(i) appears to be faster than the regular expression alternative. In my test on jsPerf the RegExp option performs 66% slower in Chrome 36 (and slightly slower in Firefox 31).
Here's a cleaned-up version of the original validation code that receives a string and returns true or false:
function isAlphaNumeric(str) {
var code, i, len;
for (i = 0, len = str.length; i < len; i++) {
code = str.charCodeAt(i);
if (!(code > 47 && code < 58) && // numeric (0-9)
!(code > 64 && code < 91) && // upper alpha (A-Z)
!(code > 96 && code < 123)) { // lower alpha (a-z)
return false;
}
}
return true;
};
Of course, there may be other considerations, such as readability. A one-line regular expression is definitely prettier to look at. But if you're strictly concerned with speed, you may want to consider this alternative.
12
Programmers love the look of code, but you see its inner beauty.
– Ziggy
Sep 16 '14 at 3:14
Interesting alternative approach - never even crossed my mind. I came here with only regex in mind!
– ozzy432836
Oct 10 '18 at 13:01
The answer that makes you think and makes you understand what it means "programming". I use your way of thinking, in my answer
– Oscar Zarrus
Nov 20 '18 at 1:16
add a comment |
The asker's original inclination to use str.charCodeAt(i) appears to be faster than the regular expression alternative. In my test on jsPerf the RegExp option performs 66% slower in Chrome 36 (and slightly slower in Firefox 31).
Here's a cleaned-up version of the original validation code that receives a string and returns true or false:
function isAlphaNumeric(str) {
var code, i, len;
for (i = 0, len = str.length; i < len; i++) {
code = str.charCodeAt(i);
if (!(code > 47 && code < 58) && // numeric (0-9)
!(code > 64 && code < 91) && // upper alpha (A-Z)
!(code > 96 && code < 123)) { // lower alpha (a-z)
return false;
}
}
return true;
};
Of course, there may be other considerations, such as readability. A one-line regular expression is definitely prettier to look at. But if you're strictly concerned with speed, you may want to consider this alternative.
12
Programmers love the look of code, but you see its inner beauty.
– Ziggy
Sep 16 '14 at 3:14
Interesting alternative approach - never even crossed my mind. I came here with only regex in mind!
– ozzy432836
Oct 10 '18 at 13:01
The answer that makes you think and makes you understand what it means "programming". I use your way of thinking, in my answer
– Oscar Zarrus
Nov 20 '18 at 1:16
add a comment |
The asker's original inclination to use str.charCodeAt(i) appears to be faster than the regular expression alternative. In my test on jsPerf the RegExp option performs 66% slower in Chrome 36 (and slightly slower in Firefox 31).
Here's a cleaned-up version of the original validation code that receives a string and returns true or false:
function isAlphaNumeric(str) {
var code, i, len;
for (i = 0, len = str.length; i < len; i++) {
code = str.charCodeAt(i);
if (!(code > 47 && code < 58) && // numeric (0-9)
!(code > 64 && code < 91) && // upper alpha (A-Z)
!(code > 96 && code < 123)) { // lower alpha (a-z)
return false;
}
}
return true;
};
Of course, there may be other considerations, such as readability. A one-line regular expression is definitely prettier to look at. But if you're strictly concerned with speed, you may want to consider this alternative.
The asker's original inclination to use str.charCodeAt(i) appears to be faster than the regular expression alternative. In my test on jsPerf the RegExp option performs 66% slower in Chrome 36 (and slightly slower in Firefox 31).
Here's a cleaned-up version of the original validation code that receives a string and returns true or false:
function isAlphaNumeric(str) {
var code, i, len;
for (i = 0, len = str.length; i < len; i++) {
code = str.charCodeAt(i);
if (!(code > 47 && code < 58) && // numeric (0-9)
!(code > 64 && code < 91) && // upper alpha (A-Z)
!(code > 96 && code < 123)) { // lower alpha (a-z)
return false;
}
}
return true;
};
Of course, there may be other considerations, such as readability. A one-line regular expression is definitely prettier to look at. But if you're strictly concerned with speed, you may want to consider this alternative.
answered Aug 17 '14 at 18:26
Michael Martin-SmuckerMichael Martin-Smucker
3,65132234
3,65132234
12
Programmers love the look of code, but you see its inner beauty.
– Ziggy
Sep 16 '14 at 3:14
Interesting alternative approach - never even crossed my mind. I came here with only regex in mind!
– ozzy432836
Oct 10 '18 at 13:01
The answer that makes you think and makes you understand what it means "programming". I use your way of thinking, in my answer
– Oscar Zarrus
Nov 20 '18 at 1:16
add a comment |
12
Programmers love the look of code, but you see its inner beauty.
– Ziggy
Sep 16 '14 at 3:14
Interesting alternative approach - never even crossed my mind. I came here with only regex in mind!
– ozzy432836
Oct 10 '18 at 13:01
The answer that makes you think and makes you understand what it means "programming". I use your way of thinking, in my answer
– Oscar Zarrus
Nov 20 '18 at 1:16
12
12
Programmers love the look of code, but you see its inner beauty.
– Ziggy
Sep 16 '14 at 3:14
Programmers love the look of code, but you see its inner beauty.
– Ziggy
Sep 16 '14 at 3:14
Interesting alternative approach - never even crossed my mind. I came here with only regex in mind!
– ozzy432836
Oct 10 '18 at 13:01
Interesting alternative approach - never even crossed my mind. I came here with only regex in mind!
– ozzy432836
Oct 10 '18 at 13:01
The answer that makes you think and makes you understand what it means "programming". I use your way of thinking, in my answer
– Oscar Zarrus
Nov 20 '18 at 1:16
The answer that makes you think and makes you understand what it means "programming". I use your way of thinking, in my answer
– Oscar Zarrus
Nov 20 '18 at 1:16
add a comment |
You don't need to do it one at a time. Just do a test for any that are not alpha-numeric. If one is found, the validation fails.
function validateCode(){
var TCode = document.getElementById('TCode').value;
if( /[^a-zA-Z0-9]/.test( TCode ) ) {
alert('Input is not alphanumeric');
return false;
}
return true;
}
If there's at least one match of a non alpha numeric, it will return false.
add a comment |
You don't need to do it one at a time. Just do a test for any that are not alpha-numeric. If one is found, the validation fails.
function validateCode(){
var TCode = document.getElementById('TCode').value;
if( /[^a-zA-Z0-9]/.test( TCode ) ) {
alert('Input is not alphanumeric');
return false;
}
return true;
}
If there's at least one match of a non alpha numeric, it will return false.
add a comment |
You don't need to do it one at a time. Just do a test for any that are not alpha-numeric. If one is found, the validation fails.
function validateCode(){
var TCode = document.getElementById('TCode').value;
if( /[^a-zA-Z0-9]/.test( TCode ) ) {
alert('Input is not alphanumeric');
return false;
}
return true;
}
If there's at least one match of a non alpha numeric, it will return false.
You don't need to do it one at a time. Just do a test for any that are not alpha-numeric. If one is found, the validation fails.
function validateCode(){
var TCode = document.getElementById('TCode').value;
if( /[^a-zA-Z0-9]/.test( TCode ) ) {
alert('Input is not alphanumeric');
return false;
}
return true;
}
If there's at least one match of a non alpha numeric, it will return false.
answered Dec 13 '10 at 22:52
user113716user113716
261k56401418
261k56401418
add a comment |
add a comment |
Check it with a regex.
Javascript regexen don't have POSIX character classes, so you have to write character ranges manually:
if (!input_string.match(/^[0-9a-z]+$/))
show_error_or_something()
Here ^ means beginning of string and $ means end of string, and [0-9a-z]+ means one or more of character from 0 to 9 OR from a to z.
More information on Javascript regexen here:
https://developer.mozilla.org/en/JavaScript/Guide/Regular_Expressions
12
+1 for explaining the basic regex and linking to a guide, rather than giving the user a "magic string".
– Charles Burns
Apr 29 '13 at 16:46
5
you need to add A-Z
– inor
Jul 23 '14 at 4:56
1
@inor you can just add 'i' at the end of the regex to specify case insensitivity, .i.e./^[a-z0-9]+$/iand this will cover both lower and upper case letters
– LJH
Jul 26 '18 at 17:50
add a comment |
Check it with a regex.
Javascript regexen don't have POSIX character classes, so you have to write character ranges manually:
if (!input_string.match(/^[0-9a-z]+$/))
show_error_or_something()
Here ^ means beginning of string and $ means end of string, and [0-9a-z]+ means one or more of character from 0 to 9 OR from a to z.
More information on Javascript regexen here:
https://developer.mozilla.org/en/JavaScript/Guide/Regular_Expressions
12
+1 for explaining the basic regex and linking to a guide, rather than giving the user a "magic string".
– Charles Burns
Apr 29 '13 at 16:46
5
you need to add A-Z
– inor
Jul 23 '14 at 4:56
1
@inor you can just add 'i' at the end of the regex to specify case insensitivity, .i.e./^[a-z0-9]+$/iand this will cover both lower and upper case letters
– LJH
Jul 26 '18 at 17:50
add a comment |
Check it with a regex.
Javascript regexen don't have POSIX character classes, so you have to write character ranges manually:
if (!input_string.match(/^[0-9a-z]+$/))
show_error_or_something()
Here ^ means beginning of string and $ means end of string, and [0-9a-z]+ means one or more of character from 0 to 9 OR from a to z.
More information on Javascript regexen here:
https://developer.mozilla.org/en/JavaScript/Guide/Regular_Expressions
Check it with a regex.
Javascript regexen don't have POSIX character classes, so you have to write character ranges manually:
if (!input_string.match(/^[0-9a-z]+$/))
show_error_or_something()
Here ^ means beginning of string and $ means end of string, and [0-9a-z]+ means one or more of character from 0 to 9 OR from a to z.
More information on Javascript regexen here:
https://developer.mozilla.org/en/JavaScript/Guide/Regular_Expressions
answered Dec 28 '11 at 8:44
Mischa ArefievMischa Arefiev
3,04111727
3,04111727
12
+1 for explaining the basic regex and linking to a guide, rather than giving the user a "magic string".
– Charles Burns
Apr 29 '13 at 16:46
5
you need to add A-Z
– inor
Jul 23 '14 at 4:56
1
@inor you can just add 'i' at the end of the regex to specify case insensitivity, .i.e./^[a-z0-9]+$/iand this will cover both lower and upper case letters
– LJH
Jul 26 '18 at 17:50
add a comment |
12
+1 for explaining the basic regex and linking to a guide, rather than giving the user a "magic string".
– Charles Burns
Apr 29 '13 at 16:46
5
you need to add A-Z
– inor
Jul 23 '14 at 4:56
1
@inor you can just add 'i' at the end of the regex to specify case insensitivity, .i.e./^[a-z0-9]+$/iand this will cover both lower and upper case letters
– LJH
Jul 26 '18 at 17:50
12
12
+1 for explaining the basic regex and linking to a guide, rather than giving the user a "magic string".
– Charles Burns
Apr 29 '13 at 16:46
+1 for explaining the basic regex and linking to a guide, rather than giving the user a "magic string".
– Charles Burns
Apr 29 '13 at 16:46
5
5
you need to add A-Z
– inor
Jul 23 '14 at 4:56
you need to add A-Z
– inor
Jul 23 '14 at 4:56
1
1
@inor you can just add 'i' at the end of the regex to specify case insensitivity, .i.e.
/^[a-z0-9]+$/i and this will cover both lower and upper case letters– LJH
Jul 26 '18 at 17:50
@inor you can just add 'i' at the end of the regex to specify case insensitivity, .i.e.
/^[a-z0-9]+$/i and this will cover both lower and upper case letters– LJH
Jul 26 '18 at 17:50
add a comment |
// On keypress event call the following method
function AlphaNumCheck(e) {
var charCode = (e.which) ? e.which : e.keyCode;
if (charCode == 8) return true;
var keynum;
var keychar;
var charcheck = /[a-zA-Z0-9]/;
if (window.event) // IE
{
keynum = e.keyCode;
}
else {
if (e.which) // Netscape/Firefox/Opera
{
keynum = e.which;
}
else return true;
}
keychar = String.fromCharCode(keynum);
return charcheck.test(keychar);
}
Further, this article also helps to understand JavaScript alphanumeric validation.
add a comment |
// On keypress event call the following method
function AlphaNumCheck(e) {
var charCode = (e.which) ? e.which : e.keyCode;
if (charCode == 8) return true;
var keynum;
var keychar;
var charcheck = /[a-zA-Z0-9]/;
if (window.event) // IE
{
keynum = e.keyCode;
}
else {
if (e.which) // Netscape/Firefox/Opera
{
keynum = e.which;
}
else return true;
}
keychar = String.fromCharCode(keynum);
return charcheck.test(keychar);
}
Further, this article also helps to understand JavaScript alphanumeric validation.
add a comment |
// On keypress event call the following method
function AlphaNumCheck(e) {
var charCode = (e.which) ? e.which : e.keyCode;
if (charCode == 8) return true;
var keynum;
var keychar;
var charcheck = /[a-zA-Z0-9]/;
if (window.event) // IE
{
keynum = e.keyCode;
}
else {
if (e.which) // Netscape/Firefox/Opera
{
keynum = e.which;
}
else return true;
}
keychar = String.fromCharCode(keynum);
return charcheck.test(keychar);
}
Further, this article also helps to understand JavaScript alphanumeric validation.
// On keypress event call the following method
function AlphaNumCheck(e) {
var charCode = (e.which) ? e.which : e.keyCode;
if (charCode == 8) return true;
var keynum;
var keychar;
var charcheck = /[a-zA-Z0-9]/;
if (window.event) // IE
{
keynum = e.keyCode;
}
else {
if (e.which) // Netscape/Firefox/Opera
{
keynum = e.which;
}
else return true;
}
keychar = String.fromCharCode(keynum);
return charcheck.test(keychar);
}
Further, this article also helps to understand JavaScript alphanumeric validation.
edited Dec 20 '13 at 16:19
Oybek
4,74632244
4,74632244
answered Dec 29 '11 at 4:27
NeerajanNeerajan
1341212
1341212
add a comment |
add a comment |
I would create a String prototype method:
String.prototype.isAlphaNumeric = function() {
var regExp = /^[A-Za-z0-9]+$/;
return (this.match(regExp));
};
Then, the usage would be:
var TCode = document.getElementById('TCode').value;
return TCode.isAlphaNumeric()
3
Maintainable JavaScript: Don’t modify objects you don’t own
– SeinopSys
Apr 28 '15 at 9:54
2
DJDavid98: I don't think that the rule "don't modify objects you don't own" applies here. Justin was just extending the capabilities of String, not modifying existing functionalities. For perspective, in C# world, that would be considered as a perfectly valid usage of an extension method. Even if some day "String.isAlphaNumeric(): boolean" would be implemented by browser manufacturers, neither the signature nor action would actualy change, so I can't see any reductions of maintainability in this particular example. That something is a rule doesn't imply that there are no exceptions.
– Risto Välimäki
Jun 8 '15 at 6:38
add a comment |
I would create a String prototype method:
String.prototype.isAlphaNumeric = function() {
var regExp = /^[A-Za-z0-9]+$/;
return (this.match(regExp));
};
Then, the usage would be:
var TCode = document.getElementById('TCode').value;
return TCode.isAlphaNumeric()
3
Maintainable JavaScript: Don’t modify objects you don’t own
– SeinopSys
Apr 28 '15 at 9:54
2
DJDavid98: I don't think that the rule "don't modify objects you don't own" applies here. Justin was just extending the capabilities of String, not modifying existing functionalities. For perspective, in C# world, that would be considered as a perfectly valid usage of an extension method. Even if some day "String.isAlphaNumeric(): boolean" would be implemented by browser manufacturers, neither the signature nor action would actualy change, so I can't see any reductions of maintainability in this particular example. That something is a rule doesn't imply that there are no exceptions.
– Risto Välimäki
Jun 8 '15 at 6:38
add a comment |
I would create a String prototype method:
String.prototype.isAlphaNumeric = function() {
var regExp = /^[A-Za-z0-9]+$/;
return (this.match(regExp));
};
Then, the usage would be:
var TCode = document.getElementById('TCode').value;
return TCode.isAlphaNumeric()
I would create a String prototype method:
String.prototype.isAlphaNumeric = function() {
var regExp = /^[A-Za-z0-9]+$/;
return (this.match(regExp));
};
Then, the usage would be:
var TCode = document.getElementById('TCode').value;
return TCode.isAlphaNumeric()
answered Jan 4 '14 at 18:30
JustinJustin
1,03811427
1,03811427
3
Maintainable JavaScript: Don’t modify objects you don’t own
– SeinopSys
Apr 28 '15 at 9:54
2
DJDavid98: I don't think that the rule "don't modify objects you don't own" applies here. Justin was just extending the capabilities of String, not modifying existing functionalities. For perspective, in C# world, that would be considered as a perfectly valid usage of an extension method. Even if some day "String.isAlphaNumeric(): boolean" would be implemented by browser manufacturers, neither the signature nor action would actualy change, so I can't see any reductions of maintainability in this particular example. That something is a rule doesn't imply that there are no exceptions.
– Risto Välimäki
Jun 8 '15 at 6:38
add a comment |
3
Maintainable JavaScript: Don’t modify objects you don’t own
– SeinopSys
Apr 28 '15 at 9:54
2
DJDavid98: I don't think that the rule "don't modify objects you don't own" applies here. Justin was just extending the capabilities of String, not modifying existing functionalities. For perspective, in C# world, that would be considered as a perfectly valid usage of an extension method. Even if some day "String.isAlphaNumeric(): boolean" would be implemented by browser manufacturers, neither the signature nor action would actualy change, so I can't see any reductions of maintainability in this particular example. That something is a rule doesn't imply that there are no exceptions.
– Risto Välimäki
Jun 8 '15 at 6:38
3
3
Maintainable JavaScript: Don’t modify objects you don’t own
– SeinopSys
Apr 28 '15 at 9:54
Maintainable JavaScript: Don’t modify objects you don’t own
– SeinopSys
Apr 28 '15 at 9:54
2
2
DJDavid98: I don't think that the rule "don't modify objects you don't own" applies here. Justin was just extending the capabilities of String, not modifying existing functionalities. For perspective, in C# world, that would be considered as a perfectly valid usage of an extension method. Even if some day "String.isAlphaNumeric(): boolean" would be implemented by browser manufacturers, neither the signature nor action would actualy change, so I can't see any reductions of maintainability in this particular example. That something is a rule doesn't imply that there are no exceptions.
– Risto Välimäki
Jun 8 '15 at 6:38
DJDavid98: I don't think that the rule "don't modify objects you don't own" applies here. Justin was just extending the capabilities of String, not modifying existing functionalities. For perspective, in C# world, that would be considered as a perfectly valid usage of an extension method. Even if some day "String.isAlphaNumeric(): boolean" would be implemented by browser manufacturers, neither the signature nor action would actualy change, so I can't see any reductions of maintainability in this particular example. That something is a rule doesn't imply that there are no exceptions.
– Risto Välimäki
Jun 8 '15 at 6:38
add a comment |
Excuse me all, no controversy. But for the community to grow as it has grown me in these years, it is good to make some notes.
The real alphanumeric string is like "0a0a0a0b0c0d" and not like "000000" or "qwertyuio".
All the answers I read here, returned true in both cases. And forgive me, IMHO, this is not right.
If I want to check if my "00000" string is alphanum, my "human" answer is unquestionably FALSE.
Why? Simple. I cannot find any letter char. So, is a simple numeric string [0-9].
On the other hand, if I wanted to check my "abcdefg" string, my "human" answer is even FALSE. I don't see numbers, so it's not alphanumeric. Just alpha [a-zA-Z].
The Michael Martin-Smucker's answer has been illuminating.
However he was aimed at achieving better performance instead of regex. This is true, using a low level way there's a better perfomance. But results it's the same.
The strings "0123456789" (only numeric), "qwertyuiop" (only alpha) and "0a1b2c3d4f4g" (alphanumeric) returns TRUE as alphanumeric. Same regex /^[a-z0-9]+$/i way.
The reason why the regex does not work is as simple as obvious. The syntax indicates or, not and.
So, if is it only numeric or if is it only letters, regex returns true.
But, the Michael Martin-Smucker's answer was nevertheless illuminating. For me.
It allowed me to think at "low level", to create a real function that unambiguous
processes an alphanumeric string. I called it like PHP relative function ctype_alnum.
Here's the code:
function ctype_alnum(str) {
var code, i, len;
var isNumeric = false, isAlpha = false; //I assume that it is all non-alphanumeric
for (i = 0, len = str.length; i < len; i++) {
code = str.charCodeAt(i);
switch (true){
case code > 47 && code < 58: // check if 0-9
isNumeric = true;
break;
case (code > 64 && code < 91) || (code > 96 && code < 123): //check if A-Z or a-z
isAlpha = true;
break;
default: // not 0-9, not A-Z or a-z
return false; //stop function with false result, no more checks
}
}
return isNumeric && isAlpha; //return the loop results, if both are true, the string is certainly alphanumeric
};
... and here's the DEMO
I came to this discussion because I was looking for an alternative in javascript to the PHP function. I didn't find the answer "ready-to-go", but as often happens on Stackoverflow, the concept of knowledge and comparison with each other is something sublime, that leads you to think about someone's answer and find together the solution you were looking for, but you didn't think you knew it.
And share it!
Best
Oscar
add a comment |
Excuse me all, no controversy. But for the community to grow as it has grown me in these years, it is good to make some notes.
The real alphanumeric string is like "0a0a0a0b0c0d" and not like "000000" or "qwertyuio".
All the answers I read here, returned true in both cases. And forgive me, IMHO, this is not right.
If I want to check if my "00000" string is alphanum, my "human" answer is unquestionably FALSE.
Why? Simple. I cannot find any letter char. So, is a simple numeric string [0-9].
On the other hand, if I wanted to check my "abcdefg" string, my "human" answer is even FALSE. I don't see numbers, so it's not alphanumeric. Just alpha [a-zA-Z].
The Michael Martin-Smucker's answer has been illuminating.
However he was aimed at achieving better performance instead of regex. This is true, using a low level way there's a better perfomance. But results it's the same.
The strings "0123456789" (only numeric), "qwertyuiop" (only alpha) and "0a1b2c3d4f4g" (alphanumeric) returns TRUE as alphanumeric. Same regex /^[a-z0-9]+$/i way.
The reason why the regex does not work is as simple as obvious. The syntax indicates or, not and.
So, if is it only numeric or if is it only letters, regex returns true.
But, the Michael Martin-Smucker's answer was nevertheless illuminating. For me.
It allowed me to think at "low level", to create a real function that unambiguous
processes an alphanumeric string. I called it like PHP relative function ctype_alnum.
Here's the code:
function ctype_alnum(str) {
var code, i, len;
var isNumeric = false, isAlpha = false; //I assume that it is all non-alphanumeric
for (i = 0, len = str.length; i < len; i++) {
code = str.charCodeAt(i);
switch (true){
case code > 47 && code < 58: // check if 0-9
isNumeric = true;
break;
case (code > 64 && code < 91) || (code > 96 && code < 123): //check if A-Z or a-z
isAlpha = true;
break;
default: // not 0-9, not A-Z or a-z
return false; //stop function with false result, no more checks
}
}
return isNumeric && isAlpha; //return the loop results, if both are true, the string is certainly alphanumeric
};
... and here's the DEMO
I came to this discussion because I was looking for an alternative in javascript to the PHP function. I didn't find the answer "ready-to-go", but as often happens on Stackoverflow, the concept of knowledge and comparison with each other is something sublime, that leads you to think about someone's answer and find together the solution you were looking for, but you didn't think you knew it.
And share it!
Best
Oscar
add a comment |
Excuse me all, no controversy. But for the community to grow as it has grown me in these years, it is good to make some notes.
The real alphanumeric string is like "0a0a0a0b0c0d" and not like "000000" or "qwertyuio".
All the answers I read here, returned true in both cases. And forgive me, IMHO, this is not right.
If I want to check if my "00000" string is alphanum, my "human" answer is unquestionably FALSE.
Why? Simple. I cannot find any letter char. So, is a simple numeric string [0-9].
On the other hand, if I wanted to check my "abcdefg" string, my "human" answer is even FALSE. I don't see numbers, so it's not alphanumeric. Just alpha [a-zA-Z].
The Michael Martin-Smucker's answer has been illuminating.
However he was aimed at achieving better performance instead of regex. This is true, using a low level way there's a better perfomance. But results it's the same.
The strings "0123456789" (only numeric), "qwertyuiop" (only alpha) and "0a1b2c3d4f4g" (alphanumeric) returns TRUE as alphanumeric. Same regex /^[a-z0-9]+$/i way.
The reason why the regex does not work is as simple as obvious. The syntax indicates or, not and.
So, if is it only numeric or if is it only letters, regex returns true.
But, the Michael Martin-Smucker's answer was nevertheless illuminating. For me.
It allowed me to think at "low level", to create a real function that unambiguous
processes an alphanumeric string. I called it like PHP relative function ctype_alnum.
Here's the code:
function ctype_alnum(str) {
var code, i, len;
var isNumeric = false, isAlpha = false; //I assume that it is all non-alphanumeric
for (i = 0, len = str.length; i < len; i++) {
code = str.charCodeAt(i);
switch (true){
case code > 47 && code < 58: // check if 0-9
isNumeric = true;
break;
case (code > 64 && code < 91) || (code > 96 && code < 123): //check if A-Z or a-z
isAlpha = true;
break;
default: // not 0-9, not A-Z or a-z
return false; //stop function with false result, no more checks
}
}
return isNumeric && isAlpha; //return the loop results, if both are true, the string is certainly alphanumeric
};
... and here's the DEMO
I came to this discussion because I was looking for an alternative in javascript to the PHP function. I didn't find the answer "ready-to-go", but as often happens on Stackoverflow, the concept of knowledge and comparison with each other is something sublime, that leads you to think about someone's answer and find together the solution you were looking for, but you didn't think you knew it.
And share it!
Best
Oscar
Excuse me all, no controversy. But for the community to grow as it has grown me in these years, it is good to make some notes.
The real alphanumeric string is like "0a0a0a0b0c0d" and not like "000000" or "qwertyuio".
All the answers I read here, returned true in both cases. And forgive me, IMHO, this is not right.
If I want to check if my "00000" string is alphanum, my "human" answer is unquestionably FALSE.
Why? Simple. I cannot find any letter char. So, is a simple numeric string [0-9].
On the other hand, if I wanted to check my "abcdefg" string, my "human" answer is even FALSE. I don't see numbers, so it's not alphanumeric. Just alpha [a-zA-Z].
The Michael Martin-Smucker's answer has been illuminating.
However he was aimed at achieving better performance instead of regex. This is true, using a low level way there's a better perfomance. But results it's the same.
The strings "0123456789" (only numeric), "qwertyuiop" (only alpha) and "0a1b2c3d4f4g" (alphanumeric) returns TRUE as alphanumeric. Same regex /^[a-z0-9]+$/i way.
The reason why the regex does not work is as simple as obvious. The syntax indicates or, not and.
So, if is it only numeric or if is it only letters, regex returns true.
But, the Michael Martin-Smucker's answer was nevertheless illuminating. For me.
It allowed me to think at "low level", to create a real function that unambiguous
processes an alphanumeric string. I called it like PHP relative function ctype_alnum.
Here's the code:
function ctype_alnum(str) {
var code, i, len;
var isNumeric = false, isAlpha = false; //I assume that it is all non-alphanumeric
for (i = 0, len = str.length; i < len; i++) {
code = str.charCodeAt(i);
switch (true){
case code > 47 && code < 58: // check if 0-9
isNumeric = true;
break;
case (code > 64 && code < 91) || (code > 96 && code < 123): //check if A-Z or a-z
isAlpha = true;
break;
default: // not 0-9, not A-Z or a-z
return false; //stop function with false result, no more checks
}
}
return isNumeric && isAlpha; //return the loop results, if both are true, the string is certainly alphanumeric
};
... and here's the DEMO
I came to this discussion because I was looking for an alternative in javascript to the PHP function. I didn't find the answer "ready-to-go", but as often happens on Stackoverflow, the concept of knowledge and comparison with each other is something sublime, that leads you to think about someone's answer and find together the solution you were looking for, but you didn't think you knew it.
And share it!
Best
Oscar
edited Nov 20 '18 at 12:41
answered Nov 20 '18 at 1:12
Oscar ZarrusOscar Zarrus
4511515
4511515
add a comment |
add a comment |
protected by Robert Harvey♦ Dec 29 '11 at 5:21
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?
1
Depends how you define "best". Most of the answers below suggest regex, which performs much slower than your original code. I've cleaned up your code a bit, which actually performs very well.
– Michael Martin-Smucker
Aug 17 '14 at 18:31