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
8 Answers
Reset to default 196However, 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
[-\._]
- means hyphen, dot and underscore[\.-_]
- 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
本文标签:
版权声明:本文标题:regex - Alphanumeric, dash and underscore but no spaces regular expression check JavaScript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736799088a1953409.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论