admin管理员组

文章数量:1134067

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

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'); }
Share Improve this question edited Nov 27, 2017 at 22:45 Donald Duck 8,85123 gold badges79 silver badges102 bronze badges asked May 4, 2011 at 17:50 TomTom 4,57717 gold badges61 silver badges92 bronze badges 1
  • 7 I like Andy E's answer below. Also, you might want to checkout gskinner.com/RegExr for quick regex editing. It's... pretty sweet. – pixelbobby Commented May 4, 2011 at 17:55
Add a comment  | 

8 Answers 8

Reset to default 196

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.

This is the most concise syntax I could find for a regex expression to be used for this check:

const regex = /^[\w-]+$/;

You shouldn't use String.match but RegExp.prototype.test (i.e. /abc/.test("abcd")) instead of String.search() if you're only interested in a boolean value. You also need to repeat your character class as explained in the answer by Andy E:

var regexp = /^[a-zA-Z0-9-_]+$/;

Got stupid error. So post here, if anyone find it useful

  1. [-\._] - means hyphen, dot and underscore
  2. [\.-_] - means all signs in range from dot to underscore

Try this

"[A-Za-z0-9_-]+"

Should allow underscores and hyphens

try this one, it is working fine for me.

"^([a-zA-Z])[a-zA-Z0-9-_]*$"

Don't escape the underscore. Might be causing some whackness.

Small change from the others. The others will allow multiple consecutive hyphens and underscores, and trailing hyphens and underscores. To allow only one consecutive hyphen or underscore, and not trailing hyphens and underscores:

([0-9A-Z])([_-]?[0-9A-Z])*

this will allow:

A, A1, A_1, AA-99-22_BC

but will not allow:

_, -A, A-, A--1, A_-1

本文标签: