javascript只允许字母数字和连字符 - 文本字段中的值 [英] javascript only allow alphanumeric and hyphen - value in text field

查看:55
本文介绍了javascript只允许字母数字和连字符 - 文本字段中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文本字段,我正在读取其值.我只想允许字母数字字符和连字符 - 值.

I have a text field, whose value I am reading. I want to only allow alphanumeric characters and hyphen - value.

如果我输入 abc$d 或 w2w,2 或 we&*23 等值,我目前使用的正则表达式似乎不会触发

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.

推荐答案

访问输入的 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]+$/

这篇关于javascript只允许字母数字和连字符 - 文本字段中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆