Alphanumeric, dash and underscore but no spaces regular expression check JavaScript

JavascriptRegex

Javascript Problem Overview


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

Javascript Solutions


Solution 1 - Javascript

> 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.

Solution 2 - Javascript

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

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

Solution 3 - Javascript

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-_]+$/;

Solution 4 - Javascript

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

Solution 5 - Javascript

Try this

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

Should allow underscores and hyphens

Solution 6 - Javascript

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

Solution 7 - Javascript

try this one, it is working fine for me.

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTomView Question on Stackoverflow
Solution 1 - JavascriptAndy EView Answer on Stackoverflow
Solution 2 - JavascriptGrant HumphriesView Answer on Stackoverflow
Solution 3 - JavascriptsaphtView Answer on Stackoverflow
Solution 4 - JavascriptIvan IvanovView Answer on Stackoverflow
Solution 5 - JavascriptAkash YellappaView Answer on Stackoverflow
Solution 6 - JavascriptDavid FellsView Answer on Stackoverflow
Solution 7 - JavascriptSantosh ShindeView Answer on Stackoverflow