I have 2 text inputs which are related to each other and I need to validate once user tabs out of both the input text fields. This is a snapshot:
And the HTML counterpart:
<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>
My javascript code for validating the 2 text fields of land phone:
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;
}
And the code which triggers this validation is blur: (I have also tried focusout)
$(".land_phone_field").blur(function () {
performLandPhoneValidationOnDiv($(this).closest(".land_phone_div"));
});
Problem: As you can see in the first image, as soon as I tab out from first field, validation is triggered even before user attempts to enter something in the second section of the phone field.
To avoid this I have tried the following in the performLandPhoneValidationOnDiv callback after the event is triggered:
var phoneFieldsHasFocus = $(areaCodeField).is(":focus") || $(phoneField).is(":focus");
And:
var phoneFieldsHasFocus = $(landphoneDiv).is(":focus");
Both return false as result. I suspect this is so because the blur / focusout event is triggered as soon as I tab out and even before any other element gains focus. For the same reason I tried to see if the parent contains focus in the interim by any chance, it seems not to be the case.
I can handle this situation by using booleans and set the state when user tabs out of both the fields to perform validation, but it would not be a clean solution and I want to know the best way to handle such situations.