最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

regex - javascript only allow alphanumeric and hyphen - value in text field - Stack Overflow

programmeradmin6浏览0评论

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 or onBlur or in a form onSubmit 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
Add a ment  | 

2 Answers 2

Reset to default 5

Access 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(...)

发布评论

评论列表(0)

  1. 暂无评论