admin管理员组文章数量:1327283
I have a text field, whose value I am reading. I want to only allow alphanumeric characters and hyphen - value.
The regex I have so far doesn't seem to fire if I enter values like abc$d or w2w,2 or we&*23 etc.
var someName = document.getElementById("sometextField");
if(/^[a-z0-9-]+$/i.test(someName.value))
{
alert('Name can only be alpha numeric with hypen.');
return;
}
Please help. Thanks for your help and time.
I have a text field, whose value I am reading. I want to only allow alphanumeric characters and hyphen - value.
The regex I have so far doesn't seem to fire if I enter values like abc$d or w2w,2 or we&*23 etc.
var someName = document.getElementById("sometextField");
if(/^[a-z0-9-]+$/i.test(someName.value))
{
alert('Name can only be alpha numeric with hypen.');
return;
}
Please help. Thanks for your help and time.
Share Improve this question edited Dec 28, 2011 at 21:07 Nomad asked Dec 28, 2011 at 21:01 NomadNomad 1,10012 gold badges29 silver badges42 bronze badges 3-
from where is this being called? (or is it?) Is this in
onChange
oronBlur
or in a formonSubmit
handler…? – BRPocock Commented Dec 28, 2011 at 21:16 - @BRPocock that shouldn't matter where's called from. The code snippet should fire if the condition is not met. – Nomad Commented Dec 28, 2011 at 21:22
- Curious if it were actually being called, since it seems to be correct, as written, my assumption was the handler wasn't connected or sommat. – BRPocock Commented Dec 28, 2011 at 21:31
2 Answers
Reset to default 5Access the input's value
property:
if(!/^[a-z0-9-]+$/i.test(someName.value)) {
//-------------------------^^^^^^^^^^
alert('Name can only be alpha numeric with hypen.');
return;
}
Update
To allow a hyphen only in the middle of the expression, not at the beginning or end, you can use the following. There are likely to be better ways, but this should do the job. You have three groups of [a-z0-9]+
, but the middle one also permits -
. The start and end groups don't permit -
.
/^[a-z0-9]+[a-z0-9-]+[a-z0-9]+$/
Notice that "-" is a special character. I don't know whether the regex engine of the browsers consider it been a special character. But I would reend you to escape it as "[a-z0-9\-]". Also, the negation should be put inside the class, as "[^a-z0-9\-]". And finally, it shouldn't contain a start and end mark (^ and $). So, I think it would be like /[^a-z0-9\-]/.test(...)
本文标签: regexjavascript only allow alphanumeric and hyphenvalue in text fieldStack Overflow
版权声明:本文标题:regex - javascript only allow alphanumeric and hyphen - value in text field - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742206974a2432998.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论