Quantcast
Channel: Solved » regex
Viewing all articles
Browse latest Browse all 14

Regular Expression for Alphanumeric and Underscores

$
0
0

Trying to check input against a regular expression.

The field should only allow alphanumeric characters, dashes and underscores and should NOT allow spaces.

However, the code below allows spaces.

What am I missing?

var regexp = /^[a-zA-Z0-9\-\_]$/;
var check = "checkme";
if (check.search(regexp) == -1)
    { alert('invalid'); }
else
    { alert('valid'); }

Thanks in advance.

Solution

However, the code below allows spaces.

No, it doesn’t. However, it will only match on input with a length of 1. For inputs with a length greater than or equal to 1, you need a + following the character class:

var regexp = /^[a-zA-Z0-9-_]+$/;
var check = "checkme";
if (check.search(regexp) == -1)
    { alert('invalid'); }
else
    { alert('valid'); }

Note that neither the - (in this instance) nor the _ need escaping.

The post Regular Expression for Alphanumeric and Underscores appeared first on Solved.


Viewing all articles
Browse latest Browse all 14

Trending Articles