不允许在 Javascript 验证中使用空格
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26331325/
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 Allowing Whitespace With Javascript Validation
提问by loyola
I am working on a web form that must be validated on submit. I have a field for a first name that must follow two rules when validated, the name must have at least 3 letters and there can be no spaces between any of the characters. I have gotten it to display an error message when the name is too short, but I can't figure out how to not allow whitespace.
我正在处理一个必须在提交时进行验证的 Web 表单。我有一个名字字段,在验证时必须遵循两个规则,名字必须至少有 3 个字母,并且任何字符之间不能有空格。当名称太短时,我已经让它显示错误消息,但我不知道如何禁止空格。
How can I validate this so that there are no spaces between any characters using javascript?
如何验证这一点,以便使用 javascript 的任何字符之间没有空格?
Here is my code so far:
到目前为止,这是我的代码:
<html>
<head>
<title>Project 5</title>
</head>
<body>
<form name="myForm" id="myForm" onsubmit="return validateForm()">
First Name: <input type="text" id="name"> <br>
Age: <input type="text" id="age"> <br>
Street Address: <input type="text" id="address"> <br>
State: <select>
<option value="la">LA</option>
<option value="tx">TX</option>
<option value="ok">OK</option>
<option value="mi">MI</option>
<option value="az">AZ</option>
</select> <br>
Login Password: <input type="password" id="password"> <br>
<input type="submit" value="Submit"> <br>
</form>
<script type="text/javascript">
function validateForm() {
return checkName();
}
function checkName() {
var x = document.myForm;
var input = x.name.value;
if(input.length < 3) {
alert("Please enter a name with at least 3 letters");
return false;
}
else if(input.length >= 3) {
}
}
</script>
</body>
</html>
回答by Krzysztof Jab?oński
I'd recommend using a regex for form input validation. Check examples below:
我建议使用正则表达式进行表单输入验证。检查以下示例:
shouldFailTooShort = 'ts';
shouldFailSpace = 'has space';
shouldPass = 'no-spaces';
validationRule = /^\S{3,}$/;
validationRule.test(shouldFailTooShort) === false;
validationRule.test(shouldFailSpace) === false;
validationRule.test(shouldPass) === true;
Using regular expressions one can have all validation against a field performed in one regular expression check, like presented above. For usability however I'd recommend having one rule for each validation requirement. Then different validation rules can produce different messages and user does not get confused having to read one and always same message.
使用正则表达式可以在一次正则表达式检查中针对一个字段执行所有验证,如上所示。但是,为了可用性,我建议为每个验证要求制定一个规则。然后不同的验证规则可以产生不同的消息,用户不会因为阅读一条始终相同的消息而感到困惑。
Have a peek on my favourite regular expression reference.
看一看我最喜欢的正则表达式参考。
Edit:As requested in comment, herein I present my proposal of deploying the solution. I suggest not using alert
function in production, but display the message on the page itself, e.g. in a span
element.
编辑:根据评论中的要求,在此我提出了部署解决方案的建议。我建议不要alert
在生产中使用函数,而是在页面本身上显示消息,例如在span
元素中。
HTML:
HTML:
<form name="myForm" id="myForm" onsubmit="return validateForm();">
First Name: <input type="text" id="name" /> <br />
<span id="nameErrMsg" class="error"></span> <br />
<!-- ... all your other stuff ... -->
</form>
<button id="validateTestButton" value="Validate now" onclick="validateForm();">Validate now</button>
JavaScript:
JavaScript:
validateForm = function () {
return checkName();
}
function checkName() {
var x = document.myForm;
var input = x.name.value;
var errMsgHolder = document.getElementById('nameErrMsg');
if (input.length < 3) {
errMsgHolder.innerHTML =
'Please enter a name with at least 3 letters';
return false;
} else if (!(/^\S{3,}$/.test(input))) {
errMsgHolder.innerHTML =
'Name cannot contain whitespace';
return false;
} else {
errMsgHolder.innerHTML = '';
return undefined;
}
}
Check live example in jsfiddle.
检查jsfiddle 中的实时示例。
回答by loyola
there is an option to remove white space of all the text by just using single line of code from Javascript.
有一个选项可以通过使用 Javascript 中的单行代码来删除所有文本的空格。
text=text.split(' ').join(''); // this will remove all the white space in your text.
回答by Jared Smith
for (var i=0, len = string.length; i<len; ++i) {
if (string.charAt(i) === ' ') {
alert('Name cannot have spaces!');
break;
}
}