javascript 输入表单中不允许有空白字符/空格
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19024825/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Not allow a blank character / space in a input form
提问by user123
Is it possible to not allow a blank character / space in a input form like below?
是否可以在如下所示的输入表单中不允许出现空白字符/空格?
<input type="text" value="" maxlength="30" name="email" class="formfield w0">
回答by Raidri supports Monica
Check this Fiddle. Relevant code:
检查这个Fiddle。相关代码:
$(function() {
$('#input1').on('keypress', function(e) {
if (e.which == 32){
console.log('Space Detected');
return false;
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="input1" />
回答by Andy E
Use HTML5's extended input types to apply constraint validation, which will prevent submitting the form with invalid emails in modern browsers:
使用 HTML5 的扩展输入类型来应用约束验证,这将防止在现代浏览器中提交带有无效电子邮件的表单:
<input type="email" value="" maxlength="30" name="email" class="formfield w0">
In older browsers, you can detect that the input's type is not "email", as it will default to "text" when a value is considered invalid. I'd recommend blocking the submission of the form, rather than preventing default action of the space key, which could be inadvertently circumvented by pasting or via other input methods.
在较旧的浏览器中,您可以检测到输入的类型不是“电子邮件”,因为当一个值被认为无效时,它会默认为“文本”。我建议阻止提交表单,而不是阻止空格键的默认操作,这可能会被粘贴或通过其他输入方法无意中规避。
The following code is an example of this, and should be executed after the document is ready:
下面的代码就是一个例子,应该在文档准备好后执行:
var frm = document.getElementById('myform');
if (frm.email.type === 'text') {
frm.onsubmit = function () {
if (/\s/.test(frm.email.value)) {
// Tell your user the field is invalid here, e.g.
frm.email.className = 'invalid';
// Prevent form submission
return false;
}
}
}
Working demo: http://jsfiddle.net/hgc7C/
工作演示:http: //jsfiddle.net/hgc7C/
Don't forget that this is not a substitute for server-side form validation.
不要忘记这不能替代服务器端表单验证。
回答by Raghavendra Reddy Busireddy
Yes it is possible by using javascript/JQuery.
是的,可以使用 javascript/JQuery。
If you want it for all text boxes, then do as below.
如果您希望所有文本框都使用它,请执行以下操作。
$(function() {
$('.formfield input[type=text]').on('keypress', function(e) {
if (e.which == 32)
return false;
});
});
If you want it for a specific textbox, then add an id to the textbox input and replace .formfield input[type=text]
with #textBoxId
如果你想要一个特定的文本框,然后在文本框输入中添加一个 id 并替换.formfield input[type=text]
为#textBoxId