我有一个输入字段,用户必须输入一个电话号码,而且必须是10个数字。我的脚本不起作用,我想知道如何指定'确切的10'部分。目前它还不到10个。
var contact_number = document.getElementById('number');
input = contact_number.value
if (input.length = 10){
alert("The field needs to contain 10 numbers!")
return false
}else {
return true
}
if (contact_number == ""){
alert("You need to enter a Phone Number")
return false;
}

<hr>
<!-- Clients details -->
<p>Contact Person: <input id="contact" name="contact" type="text" placeholder="Type Full Name here"></p>
<p>Contact Number: <input id="number" name="number" type="number" maxlength="10" placeholder="Type Number here"></p>
<p>Email address: <input id="email" name="email" type="email" placeholder="Type Email here"></p>
<hr>
&#13;
答案 0 :(得分:1)
您可以使用不等于运算符!=
var contact_number = document.getElementById('number');
input = contact_number.value
if (input.length != 10){
alert("The field needs to contain 10 numbers!")
return false
}else {
return true
}
if (contact_number == ""){
alert("You need to enter a Phone Number")
return false;
}
<hr>
<!-- Clients details -->
<p>Contact Person: <input id="contact" name="contact" type="text" placeholder="Type Full Name here"></p>
<p>Contact Number: <input id="number" name="number" type="number" maxlength="10" placeholder="Type Number here"></p>
<p>Email address: <input id="email" name="email" type="email" placeholder="Type Email here"></p>
<hr>
答案 1 :(得分:0)
看起来你的第一个if语句已关闭。我想你想要说不等于。你目前所拥有的不是比较,而是总是进入if语句的主体。
if (input.length != 10){
alert("The field needs to contain 10 numbers!")
return false
}