[javascript] RegEx for Javascript to allow only alphanumeric

I need to find a reg ex that only allows alphanumeric. So far, everyone I try only works if the string is alphanumeric, meaning contains both a letter and a number. I just want one what would allow either and not require both.

This question is related to javascript regex

The answer is


/^[a-z0-9]+$/i

^         Start of string
[a-z0-9]  a or b or c or ... z or 0 or 1 or ... 9
+         one or more times (change to * to allow empty string)
$         end of string    
/i        case-insensitive

Update (supporting universal characters)

if you need to this regexp supports universal character you can find list of unicode characters here.

for example: /^([a-zA-Z0-9\u0600-\u06FF\u0660-\u0669\u06F0-\u06F9 _.-]+)$/

this will support persian.


^\s*([0-9a-zA-Z]*)\s*$

or, if you want a minimum of one character:

^\s*([0-9a-zA-Z]+)\s*$

Square brackets indicate a set of characters. ^ is start of input. $ is end of input (or newline, depending on your options). \s is whitespace.

The whitespace before and after is optional.

The parentheses are the grouping operator to allow you to extract the information you want.

EDIT: removed my erroneous use of the \w character set.


JAVASCRIPT to accept only NUMBERS, ALPHABETS and SPECIAL CHARECTERS

_x000D_
_x000D_
document.getElementById("onlynumbers").onkeypress = function (e) {_x000D_
 onlyNumbers(e.key, e)_x000D_
};_x000D_
_x000D_
document.getElementById("onlyalpha").onkeypress = function (e) {_x000D_
 onlyAlpha(e.key, e)_x000D_
};_x000D_
_x000D_
document.getElementById("speclchar").onkeypress = function (e) {_x000D_
 speclChar(e.key, e)_x000D_
};_x000D_
_x000D_
function onlyNumbers(key, e) {_x000D_
 var letters = /^[0-9]/g; //g means global_x000D_
 if (!(key).match(letters)) e.preventDefault();_x000D_
}_x000D_
_x000D_
function onlyAlpha(key, e) {_x000D_
 var letters = /^[a-z]/gi; //i means ignorecase_x000D_
 if (!(key).match(letters)) e.preventDefault();_x000D_
}_x000D_
_x000D_
function speclChar(key, e) {_x000D_
 var letters = /^[0-9a-z]/gi;_x000D_
 if ((key).match(letters)) e.preventDefault();_x000D_
}
_x000D_
<html>_x000D_
   <head></head>_x000D_
   <body>_x000D_
      Enter Only Numbers: _x000D_
      <input id="onlynumbers" type="text">_x000D_
      <br><br>_x000D_
      Enter Only Alphabets: _x000D_
      <input id="onlyalpha" type="text" >_x000D_
      <br><br>_x000D_
      Enter other than Alphabets and numbers like special characters: _x000D_
      <input id="speclchar" type="text" >_x000D_
   </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_


I have string similar to Samsung Galaxy A10s 6.2-Inch (2GB,32GB ROM) Android 9.0, (13MP+2MP)+ 8MP Dual SIM 4000mAh 4G LTE Smartphone - Black (BF19)

Below is what i did:

string.replace(/[^a-zA-Z0-9 ,._-]/g, '').split(',').join('-').split(' ').join('-').toLowerCase()

Notice i allowed ,._- then use split() and join() to replace , to - and space to - respectively.

I ended up getting something like this: samsung-galaxy-a10s-6.2-inch-2gb-32gb-rom-android-9.0-13mp-2mp-8mp-dual-sim-4000mah-4g-lte-smartphone-black-bf19-20 which is what i wanted.

There might be a better solution but this is what i found working fine for me.


Save this constant

const letters = /^[a-zA-Z0-9]+$/

now, for checking part use .match()

const string = 'Hey there...' // get string from a keyup listner
let id = ''
// iterate through each letters
for (var i = 0; i < string.length; i++) {
  if (string[i].match(letters) ) {
    id += string[i]
  } else {
    // In case you want to replace with something else
    id += '-'  
  }
}
return id

It seems like many users have noticed this these regular expressions will almost certainly fail unless we are strictly working in English. But I think there is an easy way forward that would not be so limited.

  1. make a copy of your string in all UPPERCASE
  2. make a second copy in all lowercase

Any characters that match in those strings are definitely not alphabetic in nature.

let copy1 = originalString.toUpperCase();
let copy2 = originalString.toLowerCase();
for(let i=0; i<originalString.length; i++) {
    let bIsAlphabetic = (copy1[i] != copy2[i]);
}

Optionally, you can also detect numerics by just looking for digits 0 to 9.


If you wanted to return a replaced result, then this would work:

var a = 'Test123*** TEST';
var b = a.replace(/[^a-z0-9]/gi,'');
console.log(b);

This would return:

Test123TEST

Note that the gi is necessary because it means global (not just on the first match), and case-insensitive, which is why I have a-z instead of a-zA-Z. And the ^ inside the brackets means "anything not in these brackets".

WARNING: Alphanumeric is great if that's exactly what you want. But if you're using this in an international market on like a person's name or geographical area, then you need to account for unicode characters, which this won't do. For instance, if you have a name like "Âlvarö", it would make it "lvar".


Jquery to accept only NUMBERS, ALPHABETS and SPECIAL CHARECTERS

_x000D_
_x000D_
<html>_x000D_
<head>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
Enter Only Numbers: _x000D_
<input type="text" id="onlynumbers">_x000D_
<br><br>_x000D_
Enter Only Alphabets: _x000D_
<input type="text" id="onlyalpha">_x000D_
<br><br>_x000D_
Enter other than Alphabets and numbers like special characters: _x000D_
<input type="text" id="speclchar">_x000D_
_x000D_
<script>_x000D_
    $('#onlynumbers').keypress(function(e) {_x000D_
      var letters=/^[0-9]/g; //g means global_x000D_
      if(!(e.key).match(letters)) e.preventDefault();_x000D_
 });_x000D_
    _x000D_
    $('#onlyalpha').keypress(function(e) {_x000D_
      var letters=/^[a-z]/gi; //i means ignorecase_x000D_
      if(!(e.key).match(letters)) e.preventDefault();_x000D_
 });_x000D_
    _x000D_
    $('#speclchar').keypress(function(e) {_x000D_
      var letters=/^[0-9a-z]/gi; _x000D_
      if((e.key).match(letters)) e.preventDefault();_x000D_
 });_x000D_
    </script>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

**JQUERY to accept only NUMBERS , ALPHABETS and SPECIAL CHARACTERS **


<!DOCTYPE html>
    $('#onlynumbers').keypress(function(e) {
      var letters=/^[0-9]/g; //g means global
      if(!(e.key).match(letters)) e.preventDefault();
    });

    $('#onlyalpha').keypress(function(e) {
      var letters=/^[a-z]/gi; //i means ignorecase
      if(!(e.key).match(letters)) e.preventDefault();
    });

    $('#speclchar').keypress(function(e) {
      var letters=/^[0-9a-z]/gi; 
      if((e.key).match(letters)) e.preventDefault();
    });
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> 

Enter Only Numbers:

Enter Only Alphabets:

Enter other than Alphabets and numbers like special characters:

</body>
</html>

Use the word character class. The following is equivalent to a ^[a-zA-Z0-9_]+$:

^\w+$

Explanation:

  • ^ start of string
  • \w any word character (A-Z, a-z, 0-9, _).
  • $ end of string

Use /[^\w]|_/g if you don't want to match the underscore.


Instead of checking for a valid alphanumeric string, you can achieve this indirectly by checking the string for any invalid characters. Do so by checking for anything that matches the complement of the valid alphanumeric string.

/[^a-z\d]/i    

Here is an example:

var alphanumeric = "someStringHere";
var myRegEx  = /[^a-z\d]/i;
var isValid = !(myRegEx.test(alphanumeric));

Notice the logical not operator at isValid, since I'm testing whether the string is false, not whether it's valid.


Instead of checking for a valid alphanumeric string, you can achieve this indirectly by checking the string for any invalid characters. Do so by checking for anything that matches the complement of the valid alphanumeric string.

/[^a-z\d]/i    

Here is an example:

var alphanumeric = "someStringHere";
var myRegEx  = /[^a-z\d]/i;
var isValid = !(myRegEx.test(alphanumeric));

Notice the logical not operator at isValid, since I'm testing whether the string is false, not whether it's valid.


Even better than Gayan Dissanayake pointed out.

/^[-\w\s]+$/

Now ^[a-zA-Z0-9]+$ can be represented as ^\w+$

You may want to use \s instead of space. Note that \s takes care of whitespace and not only one space character.


Question is old, but it's never too late to answer

$(document).ready(function() {
  //prevent paste
  var usern_paste = document.getElementById('yourid');
  usern_paste.onpaste = e => e.preventDefault();

  //prevent copy
  var usern_drop = document.getElementById('yourid');
  usern_drop.ondrop = e => e.preventDefault();
});

$('#yourid').keypress(function (e) {
  var regex = new RegExp("^[a-zA-Z0-9\s]");
  var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
  if (regex.test(str)) {
      return true;
  }
  e.preventDefault();
  return false;
});

It seems like many users have noticed this these regular expressions will almost certainly fail unless we are strictly working in English. But I think there is an easy way forward that would not be so limited.

  1. make a copy of your string in all UPPERCASE
  2. make a second copy in all lowercase

Any characters that match in those strings are definitely not alphabetic in nature.

let copy1 = originalString.toUpperCase();
let copy2 = originalString.toLowerCase();
for(let i=0; i<originalString.length; i++) {
    let bIsAlphabetic = (copy1[i] != copy2[i]);
}

Optionally, you can also detect numerics by just looking for digits 0 to 9.


Use the word character class. The following is equivalent to a ^[a-zA-Z0-9_]+$:

^\w+$

Explanation:

  • ^ start of string
  • \w any word character (A-Z, a-z, 0-9, _).
  • $ end of string

Use /[^\w]|_/g if you don't want to match the underscore.


Jquery to accept only NUMBERS, ALPHABETS and SPECIAL CHARECTERS

_x000D_
_x000D_
<html>_x000D_
<head>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
Enter Only Numbers: _x000D_
<input type="text" id="onlynumbers">_x000D_
<br><br>_x000D_
Enter Only Alphabets: _x000D_
<input type="text" id="onlyalpha">_x000D_
<br><br>_x000D_
Enter other than Alphabets and numbers like special characters: _x000D_
<input type="text" id="speclchar">_x000D_
_x000D_
<script>_x000D_
    $('#onlynumbers').keypress(function(e) {_x000D_
      var letters=/^[0-9]/g; //g means global_x000D_
      if(!(e.key).match(letters)) e.preventDefault();_x000D_
 });_x000D_
    _x000D_
    $('#onlyalpha').keypress(function(e) {_x000D_
      var letters=/^[a-z]/gi; //i means ignorecase_x000D_
      if(!(e.key).match(letters)) e.preventDefault();_x000D_
 });_x000D_
    _x000D_
    $('#speclchar').keypress(function(e) {_x000D_
      var letters=/^[0-9a-z]/gi; _x000D_
      if((e.key).match(letters)) e.preventDefault();_x000D_
 });_x000D_
    </script>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

**JQUERY to accept only NUMBERS , ALPHABETS and SPECIAL CHARACTERS **


<!DOCTYPE html>
    $('#onlynumbers').keypress(function(e) {
      var letters=/^[0-9]/g; //g means global
      if(!(e.key).match(letters)) e.preventDefault();
    });

    $('#onlyalpha').keypress(function(e) {
      var letters=/^[a-z]/gi; //i means ignorecase
      if(!(e.key).match(letters)) e.preventDefault();
    });

    $('#speclchar').keypress(function(e) {
      var letters=/^[0-9a-z]/gi; 
      if((e.key).match(letters)) e.preventDefault();
    });
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> 

Enter Only Numbers:

Enter Only Alphabets:

Enter other than Alphabets and numbers like special characters:

</body>
</html>

Try this... Replace you field ID with #name... a-z(a to z), A-Z(A to Z), 0-9(0 to 9)

jQuery(document).ready(function($){
    $('#name').keypress(function (e) {
        var regex = new RegExp("^[a-zA-Z0-9\s]+$");
        var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
        if (regex.test(str)) {
            return true;
        }
        e.preventDefault();
        return false;
    });
});

/^([a-zA-Z0-9 _-]+)$/

the above regex allows spaces in side a string and restrict special characters.It Only allows a-z, A-Z, 0-9, Space, Underscore and dash.


Input these code to your SCRATCHPAD and see the action.

var str=String("Blah-Blah1_2,oo0.01&zz%kick").replace(/[^\w-]/ig, '');

If you wanted to return a replaced result, then this would work:

var a = 'Test123*** TEST';
var b = a.replace(/[^a-z0-9]/gi,'');
console.log(b);

This would return:

Test123TEST

Note that the gi is necessary because it means global (not just on the first match), and case-insensitive, which is why I have a-z instead of a-zA-Z. And the ^ inside the brackets means "anything not in these brackets".

WARNING: Alphanumeric is great if that's exactly what you want. But if you're using this in an international market on like a person's name or geographical area, then you need to account for unicode characters, which this won't do. For instance, if you have a name like "Âlvarö", it would make it "lvar".


Use the word character class. The following is equivalent to a ^[a-zA-Z0-9_]+$:

^\w+$

Explanation:

  • ^ start of string
  • \w any word character (A-Z, a-z, 0-9, _).
  • $ end of string

Use /[^\w]|_/g if you don't want to match the underscore.


Input these code to your SCRATCHPAD and see the action.

var str=String("Blah-Blah1_2,oo0.01&zz%kick").replace(/[^\w-]/ig, '');

Alphanumeric with case sensitive:

if (/^[a-zA-Z0-9]+$/.test("SoS007")) {
  alert("match")
}

JAVASCRIPT to accept only NUMBERS, ALPHABETS and SPECIAL CHARECTERS

_x000D_
_x000D_
document.getElementById("onlynumbers").onkeypress = function (e) {_x000D_
 onlyNumbers(e.key, e)_x000D_
};_x000D_
_x000D_
document.getElementById("onlyalpha").onkeypress = function (e) {_x000D_
 onlyAlpha(e.key, e)_x000D_
};_x000D_
_x000D_
document.getElementById("speclchar").onkeypress = function (e) {_x000D_
 speclChar(e.key, e)_x000D_
};_x000D_
_x000D_
function onlyNumbers(key, e) {_x000D_
 var letters = /^[0-9]/g; //g means global_x000D_
 if (!(key).match(letters)) e.preventDefault();_x000D_
}_x000D_
_x000D_
function onlyAlpha(key, e) {_x000D_
 var letters = /^[a-z]/gi; //i means ignorecase_x000D_
 if (!(key).match(letters)) e.preventDefault();_x000D_
}_x000D_
_x000D_
function speclChar(key, e) {_x000D_
 var letters = /^[0-9a-z]/gi;_x000D_
 if ((key).match(letters)) e.preventDefault();_x000D_
}
_x000D_
<html>_x000D_
   <head></head>_x000D_
   <body>_x000D_
      Enter Only Numbers: _x000D_
      <input id="onlynumbers" type="text">_x000D_
      <br><br>_x000D_
      Enter Only Alphabets: _x000D_
      <input id="onlyalpha" type="text" >_x000D_
      <br><br>_x000D_
      Enter other than Alphabets and numbers like special characters: _x000D_
      <input id="speclchar" type="text" >_x000D_
   </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_


I have string similar to Samsung Galaxy A10s 6.2-Inch (2GB,32GB ROM) Android 9.0, (13MP+2MP)+ 8MP Dual SIM 4000mAh 4G LTE Smartphone - Black (BF19)

Below is what i did:

string.replace(/[^a-zA-Z0-9 ,._-]/g, '').split(',').join('-').split(' ').join('-').toLowerCase()

Notice i allowed ,._- then use split() and join() to replace , to - and space to - respectively.

I ended up getting something like this: samsung-galaxy-a10s-6.2-inch-2gb-32gb-rom-android-9.0-13mp-2mp-8mp-dual-sim-4000mah-4g-lte-smartphone-black-bf19-20 which is what i wanted.

There might be a better solution but this is what i found working fine for me.


Extend the string prototype to use throughout your project

    String.prototype.alphaNumeric = function() {
        return this.replace(/[^a-z0-9]/gi,'');
    }

Usage:

    "I don't know what to say?".alphaNumeric();
    //Idontknowwhattosay

This will work

^(?=.*[a-zA-Z])(?=.*[0-9])[a-zA-Z0-9]+$

It accept only alphanumeriuc characters alone:
test cases pased :

dGgs1s23 - valid
12fUgdf  - valid,
121232   - invalid, 
abchfe   - invalid,
 abd()*  - invalid, 
42232^5$ - invalid

or

You can also try this one. this expression satisfied at least one number and one character and no other special characters

^(?=.*[0-9])(?=.*[a-zA-Z])([a-zA-Z0-9]+)$

in angular can test like:

$scope.str = '12fUgdf';
var pattern = new RegExp('^(?=.*[0-9])(?=.*[a-zA-Z])([a-zA-Z0-9]+)$');
$scope.testResult = pattern.test($scope.str);

PLUNKER DEMO

Refered:Regular expression for alphanumeric in Angularjs


^\s*([0-9a-zA-Z]*)\s*$

or, if you want a minimum of one character:

^\s*([0-9a-zA-Z]+)\s*$

Square brackets indicate a set of characters. ^ is start of input. $ is end of input (or newline, depending on your options). \s is whitespace.

The whitespace before and after is optional.

The parentheses are the grouping operator to allow you to extract the information you want.

EDIT: removed my erroneous use of the \w character set.


Try this... Replace you field ID with #name... a-z(a to z), A-Z(A to Z), 0-9(0 to 9)

jQuery(document).ready(function($){
    $('#name').keypress(function (e) {
        var regex = new RegExp("^[a-zA-Z0-9\s]+$");
        var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
        if (regex.test(str)) {
            return true;
        }
        e.preventDefault();
        return false;
    });
});

Save this constant

const letters = /^[a-zA-Z0-9]+$/

now, for checking part use .match()

const string = 'Hey there...' // get string from a keyup listner
let id = ''
// iterate through each letters
for (var i = 0; i < string.length; i++) {
  if (string[i].match(letters) ) {
    id += string[i]
  } else {
    // In case you want to replace with something else
    id += '-'  
  }
}
return id

Question is old, but it's never too late to answer

$(document).ready(function() {
  //prevent paste
  var usern_paste = document.getElementById('yourid');
  usern_paste.onpaste = e => e.preventDefault();

  //prevent copy
  var usern_drop = document.getElementById('yourid');
  usern_drop.ondrop = e => e.preventDefault();
});

$('#yourid').keypress(function (e) {
  var regex = new RegExp("^[a-zA-Z0-9\s]");
  var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
  if (regex.test(str)) {
      return true;
  }
  e.preventDefault();
  return false;
});

Even better than Gayan Dissanayake pointed out.

/^[-\w\s]+$/

Now ^[a-zA-Z0-9]+$ can be represented as ^\w+$

You may want to use \s instead of space. Note that \s takes care of whitespace and not only one space character.


^\s*([0-9a-zA-Z]*)\s*$

or, if you want a minimum of one character:

^\s*([0-9a-zA-Z]+)\s*$

Square brackets indicate a set of characters. ^ is start of input. $ is end of input (or newline, depending on your options). \s is whitespace.

The whitespace before and after is optional.

The parentheses are the grouping operator to allow you to extract the information you want.

EDIT: removed my erroneous use of the \w character set.


Alphanumeric with case sensitive:

if (/^[a-zA-Z0-9]+$/.test("SoS007")) {
  alert("match")
}

/^([a-zA-Z0-9 _-]+)$/

the above regex allows spaces in side a string and restrict special characters.It Only allows a-z, A-Z, 0-9, Space, Underscore and dash.


Use the word character class. The following is equivalent to a ^[a-zA-Z0-9_]+$:

^\w+$

Explanation:

  • ^ start of string
  • \w any word character (A-Z, a-z, 0-9, _).
  • $ end of string

Use /[^\w]|_/g if you don't want to match the underscore.


A little bit late, but this worked for me:

/[^a-z A-Z 0-9]+/g

a-z : anything from a to z.

A-Z : anything from A to Z (upper case).

0-9 : any number from 0 to 9.

It will allow anything inside square brackets, so let's say you want to allow any other character, for example, "/" and "#", the regex would be something like this:

/[^a-z A-Z 0-9 / #]+/g

This site will help you to test your regex before coding. https://regex101.com/

Feel free to modify and add anything you want into the brackets. Regards :)


^\s*([0-9a-zA-Z]*)\s*$

or, if you want a minimum of one character:

^\s*([0-9a-zA-Z]+)\s*$

Square brackets indicate a set of characters. ^ is start of input. $ is end of input (or newline, depending on your options). \s is whitespace.

The whitespace before and after is optional.

The parentheses are the grouping operator to allow you to extract the information you want.

EDIT: removed my erroneous use of the \w character set.