【发布时间】:2017-02-16 01:01:58
【问题描述】:
我有下面的代码。我希望我的最大字符输入为 10,最小为 2。但是当我输入的最小字符为 2 甚至小于 10 个字符时,我尝试了,我的文本框仍然变为红色。我不能在这里 HTML maxlength 或 minlength。
这个条件if (fname.value.match(/\S/)) 在它应该检查空格时检查文本框是否不为空。我尝试使用!= "",但是当我输入一些内容时,它会在我调试时被跳过。
function validation() {
var fname = "";
var add = "";
var message = "";
// retrieving ids
fname = document.getElementById('fname');
add = document.getElementById('add');
// white to red
if (fname.value.match(/\S/)) {
fname.style.backgroundColor = "white";
}
if ((fname != '') || (fname.value >= 10 || fname.value <= 2)) {
fname.style.backgroundColor = "red";
}
// white to red
if (add.value.match(/\S/)) {
add.style.backgroundColor = "white";
}
if ((add != '') || (add.value >= 10 || add.value <= 2)) {
add.style.backgroundColor = "red";
}
if (fname.value == "") {
alert("Firstname is empty! Enter your firstname to resume");
return false;
}
if (add.value == "") {
alert("Address is empty! Enter your address to resume");
return false;
}
}
<form onsubmit="return validation()">
Firstname:<br>
<input type="text" name="fname" id="fname">
<br> Address:
<br>
<input type="text" name="add" id="add">
<br><br>
<input type="submit" onClick="validation(); return false;" value="Submit">
</form>
【问题讨论】:
-
fname.value.match(/\S/)应该检查什么? -
@ibrahim mahrir 它应该检查用户是否有输入,而实际上检查那里是否有空格。当文本框不为空时,我尝试使用!=“”,但在调试代码时它会跳过它。
-
你为什么不直接使用
if(fname.value.length)!
标签: javascript forms validation textbox