下面的 JavaScript 只是检查字段中是否有 4 位数字,如果没有则发出警告。
但由于某种原因,如果我输入四个零 (0000),它会将其视为空字段并引发警告。
知道如何解决这个问题吗??我不是程序员,但经过数周的反复试验才将这段代码组合在一起。
function validate(){
// if ( (!isNaN($("#couponstart1").val())) || (!isNaN($("#couponstart2").val())) || (!isNaN($("#couponend1").val())) || (!isNaN($("#couponend2").val())) ) {
var all_ok = true;
var err_msg = "";
var fld = "";
if ( $("#couponstart1").val() == '' || $("#couponstart2").val() == '' || $("#couponend1").val() == '' || $("#couponend2").val() == '' ) {
all_ok = false;
err_msg += "\n - Card Numbers cannot be blank";
fld='couponstart1';
}else{
if ( isNaN($("#couponstart1").val()) || isNaN($("#couponstart2").val()) || isNaN($("#couponend1").val()) || isNaN($("#couponend2").val()) ) {
all_ok = false;
err_msg += "\n - Card Number has to be numeric";
fld='couponstart1';
}else{
if ( $("#couponstart1").val() < 1 || $("#couponstart2").val() < 1 || $("#couponend1").val() < 1 || $("#couponend2").val() < 1 ) {
all_ok = false;
err_msg += "\n - Card Numbers are not correct";
fld='couponstart1';
}else if ($("#couponstart1").val().length != 4 || $("#couponstart2").val().length != 4 || $("#couponend1").val().length != 4 || $("#couponend2").val().length < 4){
all_ok = false;
err_msg += "\n - Card Numbers are not correct";
fld='couponstart1';
}
}
}
if (all_ok == false){
alert("The following errors have taken place" + err_msg);
setFocus(fld);
}
return all_ok;
}
最佳答案
可悲的是,计算机只做我们要求的事,而不是我们想要的事。
如果你输入的是0000,你比较<
编号为1
:($("#couponstart1").val() < 1
,javascript将尝试解析值0000
到占 0
的操作数类型。所以说 0 is lower than 1
是正确的你会收到错误消息 Card number are not correct
.
让我们尝试不同的方法:
<!-- html -->
<form>
<p>
<label for="couponstart1">Coupon Start Part 1</label>
<input type="text" maxlength="4" id="couponstart1" class="validateme" />
</p>
<p>
<label for="couponstart2">Coupon Start Part 2</label>
<input type="text" maxlength="4" id="couponstart2" class="validateme" />
</p>
<p>
<label for="couponend1">Coupon End Part 1</label>
<input type="text" maxlength="4" id="couponend1" class="validateme" />
</p>
<p>
<label for="couponstart2">Coupon Start End 2</label>
<input type="text" maxlength="4" id="couponend2" class="validateme" />
</p>
<button type="button" id="testit">Test</button>
</form>
和:
/* javascript/jQuery */
$(document).ready(function(){
$("#testit").click(function(){
var rgx = /\d{4}/;
var allgood = true;
$("input.validateme").each(function(){
if( ! rgx.test( $(this).val() ) ){
alert("Card number for " + ($('label[for="' + $(this).attr("id") + '"]').text()) + " is not correct!\nPlease use 4 digits all numbers!");
$(this).select();
allgood = false;
return false;
}
});
if(allgood) alert("All good!");
});
});
基本上我们有一个包含 4 inputs
的表单与“validateme”class
。
使用 jQuery,我们循环遍历具有此类的输入,并针对正则表达式 /\d{4}/
运行它。基本上将测试一个数字( \d
)正好 4 位长( {4}
),意思是从 0000 到 9999。请注意,我们使用输入的标签来识别哪个字段不正确。
否则,一切都好。
您可以在这里修改此代码:http://jsfiddle.net/L8dcgcrs/1/
关于JavaScript 错误捕获未读取 0(零),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25537529/