RegEx for Javascript to allow only alphanumeric

2019-01-01 04:35发布

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.

12条回答
零度萤火
2楼-- · 2019-01-01 05:26
^\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.

查看更多
宁负流年不负卿
3楼-- · 2019-01-01 05:26

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.

查看更多
一个人的天荒地老
4楼-- · 2019-01-01 05:34
/^[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
查看更多
时光乱了年华
5楼-- · 2019-01-01 05:41

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.

查看更多
刘海飞了
6楼-- · 2019-01-01 05:41

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

查看更多
大哥的爱人
7楼-- · 2019-01-01 05:41

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;
    });
});
查看更多
登录 后发表回答