admin管理员组文章数量:1395159
I have the following to disallow spaces
function nospaces(t){
if(t.value.match(/\s/g)){
alert('Username Cannot Have Spaces or Full Stops');
t.value=t.value.replace(/\s/g,'');
}
}
HTML
<input type="text" name="username" value="" onkeyup="nospaces(this)"/>
It works well for spaces but how can I also disallow full stops as well?
I have the following to disallow spaces
function nospaces(t){
if(t.value.match(/\s/g)){
alert('Username Cannot Have Spaces or Full Stops');
t.value=t.value.replace(/\s/g,'');
}
}
HTML
<input type="text" name="username" value="" onkeyup="nospaces(this)"/>
It works well for spaces but how can I also disallow full stops as well?
Share Improve this question edited May 26, 2013 at 5:46 me_digvijay 5,50210 gold badges51 silver badges86 bronze badges asked May 26, 2013 at 5:42 Adam GAdam G 842 silver badges8 bronze badges3 Answers
Reset to default 3Try this
function nospaces(t){
if(t.value.match(/\s|\./g)){
alert('Username Cannot Have Spaces or Full Stops');
t.value=t.value.replace(/\s/g,'');
}
}
Below is the sample html and javscript you just wanted to add /./g for checking for .
<html>
<input type="text" name="username" value="" onkeyup="nospaces(this)"/>
<script>
function nospaces(t){
if( t.value.match(/\s/g) || t.value.match(/\./g) ){
alert('Username Cannot Have Spaces or Full Stops');
t.value= (t.value.replace(/\s/g,'') .replace(/\./g,''));
}
}
</script>
</html>
If not its not necessary to use regex you can use
if(value.indexOf('.') != -1) {
alert("dots not allowed");
}
or if required
if(value.match(/\./g) != null) {
alert("Dots not allowed");
}
本文标签: formsHow to prevent spaces and full stops in input field with javascriptStack Overflow
版权声明:本文标题:forms - How to prevent spaces and full stops in input field with javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744668077a2618654.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论