Reputation: 225
my problem with the following javascript function:
function ValidateDates() {
var valid = false;
birthD = $("#cp1_txtBirthDate").val();
initialD = $("#cp1_txtInitialDate").val();
var regexp = new RegExp("^([1-9]|(0|1|2)[0-9]|30)(/)([1-9]|1[0-2]|0[1-9])(/)((20|19|18)[0-9]{2})$");
if (birthD != "__/__/____" && initialD != "__/__/____") {
if (regexp.test(initialD) && regexp.test(birthD)) {
$.get("ValidateDates.aspx?BirthD=" + birthD + "&InitialD=" + initialD, function (data) {
if (data == 0) {
valid = true;
$("#Dates_span").html("");
}
else {
$("#Dates_span").html("*" + data);
valid = false;
}
});
}
}
return valid;
}
here when i check the variable valid i found it "false" even if its true, because the initial for it is false from the beginning of function so how to solve it and what is wrong?
Upvotes: 0
Views: 1866
Reputation: 13755
What's wrong is that $.get
is an asynchronous call, what that means is that the function doesn't wait until the result is returned from $.get
call. It just makes the call and continues execution - so valid = true
is set long after false
has been returned.
Upvotes: 1
Reputation: 284786
When you're doing an asynchronous call, you can't return a value like that. Instead, you should pass in a callback:
function ValidateDates(callback) {
var valid = false;
birthD = $("#cp1_txtBirthDate").val();
initialD = $("#cp1_txtInitialDate").val();
var regexp = new RegExp("^([1-9]|(0|1|2)[0-9]|30)(/)([1-9]|1[0-2]|0[1-9])(/)((20|19|18)[0-9]{2})$");
if (birthD != "__/__/____" && initialD != "__/__/____") {
if (regexp.test(initialD) && regexp.test(birthD)) {
$.get("ValidateDates.aspx?BirthD=" + birthD + "&InitialD=" + initialD, function(data) {
if (data == 0) {
valid = true;
$("#Dates_span").html("");
}
else {
$("#Dates_span").html("*" + data);
valid = false;
}
callback(valid);
});
}
}
}
Then, call it like:
ValidateDates(function(isValid)
{
// Do something with isValid
});
Upvotes: 6