我有两个相互关联的文本输入,我需要在输入文本字段中验证一次用户选项卡。这是一个快照:
与HTML对应:
<div class="four float_left field_div_wrapper">
<div class="padding_5">
<div class="field_title">
Telephon rumah
</div>
<div class="twelve height_30 land_phone_div">
<input type="text" id="telephon_rumah_field_1" class="three land_phone_field_1 land_phone_field">
<input type="text" id="telephon_rumah_field_2" class="eight land_phone_field_2 land_phone_field">
</div>
<div class="twelve float_left clear_left red_text display_hidden error_div_text">
This field must be numeric with 3 to 4 and 7 to 8 digits
</div>
</div>
</div>
我的javascript代码,用于验证陆地电话的2个文本字段:
function performLandPhoneValidationOnDiv(landphoneDiv) {
var landPhoneValid = true;
// Here we consider both fields (code of area and office / home phone numbers) for validation if they are non-empty
// If both the fields are empty then it is a valid entry!
var areaCodeField = $(landphoneDiv).find(".land_phone_field_1");
var phoneField = $(landphoneDiv).find(".land_phone_field_2");
// We need to check current focus and perform validations only if both the text fields do not have focus currently
// http://stackoverflow.com/a/2684561/260665
// var phoneFieldsHasFocus = $(areaCodeField).is(":focus") || $(phoneField).is(":focus");
var phoneFieldsHasFocus = $(landphoneDiv).is(":focus");
if (!phoneFieldsHasFocus) {
.
.
.
// Internal validation to check if both the fields (area & phone) has valid data
}
return landPhoneValid;
}
触发此验证的代码很模糊:(我也尝试过焦点)
$(".land_phone_field").blur(function () {
performLandPhoneValidationOnDiv($(this).closest(".land_phone_div"));
});
问题:正如您在第一张图片中看到的那样,只要我从第一个字段中跳出,即使在用户尝试在电话字段的第二部分输入内容之前,也会触发验证。
为了避免这种情况,我在触发事件后在performLandPhoneValidationOnDiv回调中尝试了以下内容:
var phoneFieldsHasFocus = $(areaCodeField).is(":focus") || $(phoneField).is(":focus");
和
var phoneFieldsHasFocus = $(landphoneDiv).is(":focus");
两者都返回false作为结果。我怀疑是这样的,因为模糊/聚焦事件会在我标签输出时立即触发,甚至在任何其他元素获得焦点之前触发。出于同样的原因,我试图通过任何机会看看父母是否在临时中包含焦点,似乎并非如此。
我可以通过使用布尔值来处理这种情况,并在用户选项卡两个字段之外设置状态以执行验证,但它不是一个干净的解决方案,我想知道处理这种情况的最佳方法。