且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

javascript只允许字母数字和连字符 - 文本字段中的值

更新时间:2021-07-23 23:02:43

访问输入的 value 属性:

if(!/^[a-z0-9-]+$/i.test(someName.value)) {
   //-------------------------^^^^^^^^^^
   alert('Name can only be alpha numeric with hypen.');
   return;
}

更新

要仅在表达式中间允许连字符,而不是在开头或结尾,可以使用以下内容.可能有更好的方法,但这应该可以解决问题.你有三组[a-z0-9]+,但中间的一组也允许-.开始和结束组不允许 -.

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