2012-06-21 78 views
0

我试图阻止用户在文本框中插入*。
这就是我想要做的,但是在这里它只检测*如果这是唯一插入的字符。例如文本如:*等
当允许的字符与*混合在一起时,它无法检测到它。例如输入如:* hjh等。
也许如何使它只替换*而不是整个字段?防止用户插入*

<script type="text/javascript"> 
    function testField(field) { 
     var regExpr = new RegExp("[^*]"); 
     if(!regExpr.test(field.value)) { 
      field.value = ""; 
     } 
    } 
</script> 

<input type="text" id="searchGamesKeyword" class="searchGamesTextBox" 
name="searchGamesKeyword" onblur="testField(this);" /> 
+2

使用keyup事件,并检查密钥号码。 –

+0

请不要对新的RegExp使用静态字符串。 JavaScript提供'RegExp'文字,这在很多方面都更好。 'var regExpr =/[^ *] /;' – Ryan

+0

@minitech - 谢谢,注意。 – user990635

回答

1

如何:

function testField(field) { 
    field.value = field.value.replace(/\*/g,""); 
} 

如图它会采取字段的当前值和一个空字符串替换任何和所有星号的问题,从onblur=testField(this)调用,使所有其他字符不变。所以,例如,"ab*cde*"将变成"abcde"

/\*/g末尾的g是一个标志,意思是全局匹配 - 没有这个标志,它只会取代第一个匹配。

你的代码没有工作的原因是你的正则表达式[^*]将匹配(即,从.test()返回true),如果有一个非星号字符的字符串中的任何位置。

2

你忘了你的正则表达式锚定到字符串的开头和结尾:new RegExp("[^*]")

试试这个:var regExpr = /^[^*]*$/ - 它要求除了*任何字符的零个或多个实例在启动和固定字符串的结尾。如果要强制除*之外的任何字符的一个或多个实例,可能/^[^*]+$/会更好(注意+)。

+0

我用[minitech的建议使用RegExp文字]更新了我的帖子(http://stackoverflow.com/questions/11130896/preventing-user-from-inserting/11130921#comment14587870_11130896) - 谢谢@minitech。 – sarnold

1
<script type="text/javascript"> 
function testField(field, event) { 
    if (event.charCode == 42) { 
     event.preventDefault(); 
    }  
} 
</script> 

<input type="text" id="searchGamesKeyword" class="searchGamesTextBox" 
name="searchGamesKeyword" onkeypress="javascript:testField(this, event);" />​ 
+0

而这里来了[我提到的选择问题](http://stackoverflow.com/questions/11130896/preventing-user-from-inserting#comment14587881_11130896)。如果用户在字段中间的某处打字,则光标将保持跳转到最后。不是一个好的体验。 – Ryan

+0

哦,我明白你的意思了,嗯,你需要捕获keypress和preventDefault(),请参阅http://stackoverflow.com/questions/1421562/how-to-stop-keypress-event-in-keydown – jchook

+1

无关:你不需要逃跑和角色类。只需使用'/ \ */g'。 – Ryan

0

这应该防止人们输入*并复制并粘贴到。请记住检查后端,因为人们可能会在浏览器中禁用JS。

使用Javascript:

function testField(f) 
{ 
    var o='',i,v=f.value; 
    for(i=0;i<v.length;i++) if(v[i]!='*')o+=v[i]; 
    f.value=o; 
} 

HTML:

<input type="text" id="searchGamesKeyword" class="searchGamesTextBox" name="searchGamesKeyword" onkeyup="testField(this);" onchange="testField(this);" /> 

DEMO:http://jsfiddle.net/martinschaer/Sbg6w/(手动优化和精缩;))

编辑: 使用的标志(c)可避免具有如果您尝试编辑迄今为止输入的内容,该插入符号位于最后。就像这样:

function testField(f) 
{ 
    var t,c,i=0,o='',x="value",v=f[x],l=v.length; 
    while(i<l){t=v[i++];if(t!='*')o+=t;else c=1} 
    if(c)f[x]=o 
} 

测试在这里:http://jsfiddle.net/martinschaer/Sbg6w/

+0

我不会在keyup(或任何关键事件)上这样做,因为更新'.value'会倾向于将光标移动到字段,因此编辑现有值非常繁琐。 (你可以添加一个单独的键控处理程序来防止该字符被输入,使用'onchange'或'onblur'中的当前函数来处理任何粘贴的更改。) – nnnnnn

+0

@nnnnnn以及如何添加标志来仅更新f.value如果*已被检测到?这会在尝试编辑值时消除该问题。我坚持要做到这一点onkeyup,所以用户得到*不允许,而不是让他们完成打字时消失......对我来说,你的解决方案不够公平:P –