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']; }
Donald Duck
7,85120 gold badges70 silver badges91 bronze badges
asked May 4, 2011 at 17:50
1
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.
bugwheels94
29.4k3 gold badges37 silver badges59 bronze badges
answered May 4, 2011 at 17:54
Andy EAndy E
330k83 gold badges469 silver badges441 bronze badges
0
This is the most concise syntax I could find for a regex expression to be used for this check:
const regex = /^[\w-]+$/;
answered Dec 14, 2017 at 2:19
Grant HumphriesGrant Humphries
2,4461 gold badge22 silver badges24 bronze badges
2
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-_]+$/;
answered May 4, 2011 at 18:18
saphtsapht
2,67917 silver badges16 bronze badges
1
Got stupid error. So post here, if anyone find it useful
[-\._]
- means hyphen, dot and underscore[\.-_]
- means all signs in range from dot to underscore
answered Jul 18, 2016 at 12:33
Ivan IvanovIvan Ivanov
2,01717 silver badges30 bronze badges
1
Try this
"[A-Za-z0-9_-]+"
Should allow underscores and hyphens
answered May 21, 2019 at 16:15
1
try this one, it is working fine for me.
"^[[a-zA-Z]][a-zA-Z0-9-_]*$"
answered Oct 14, 2019 at 9:23
Don't escape the underscore. Might be causing some whackness.
answered May 4, 2011 at 17:52
David FellsDavid Fells
6,5801 gold badge21 silver badges34 bronze badges
2