Javascript 输入字段中“不允许空格”的客户端验证
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27011061/
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
Client side validation for "No Space Allowed" in input field
提问by user4148466
In the following code I have given validation for required but its taking blank spaces also so I want validation for this line which will not allowed for not only space or not start with a space. Means it can take spaces with characters but not only blank space.
在下面的代码中,我已经对 required 进行了验证,但它也占用了空格,所以我想要验证这一行,这不仅不允许空格或不以空格开头。意味着它可以使用带有字符的空格,而不仅仅是空格。
<input type="text" required placeholder="Lastname Firstname Middlename" id="fullname" name="fullname" class="textbox">
I wants to limit or restrict file upload size in bellow line of code want same client side restriction
我想在下面的代码行中限制或限制文件上传大小想要相同的客户端限制
<input type="file" required accept=".gif,.jpeg,.png" name="image" id="image"/>
回答by Shoaib Chikate
You can use pattern attribute of HTML5 and give regex expression to avoid spaces
您可以使用 HTML5 的模式属性并给出正则表达式以避免空格
<form action="someaction">
<input type="text" id="fullname" name="fullname" required class="textbox" placeholder="Lastname Firstname Middlename" pattern="^\S+$">
<input type="submit" value="submit">
</form>
回答by Khaarkh
If you desperately want to use js:
如果你非常想使用 js:
<form onSubmit="return validateForm();">...</form>
<script type="text/javascript">
function validateForm(){
var text = this.getElementById('fullname').value;
text = text.split(' '); //we split the string in an array of strings using whitespace as separator
return (text.length == 1); //true when there is only one word, false else.
}
</script>
回答by Sujit Thombare
try following html code or javascript function --
<!DOCTYPE html>
<html>
<head>
<title>Test Page</title>
<script type="text/javascript">
function validtxt(){
var txt = document.getElementById("fullname").value ;
var len =txt.trim().length;
if (len < 1)
{
alert("Invalid Text");
}
}
</script>
</head>
<body>
<form>
<input type="text" name="fullname" id="fullname" placeholder="ok" onChange="validtxt()" />
</form>
</body>
</html>
回答by Lalit Sharma
Please try below code
请尝试以下代码
$( "#fullname" ).focusout(function() {
textValue = $.trim($(this).val());
if(textValue ==''){
$.trim($(this).val('')); //to set it blank
} else {
return true;
}
});

