Skip to content Skip to sidebar Skip to footer

Why Is My Function Returning Undefined?

The function validate() is returning undefined, when I expected it to return false or true. Why is this happening? Now I'm just typing this because stackoverflow won't let me post

Solution 1:

Return $.get() from validate; return true or false at .then() chained to $.get() call; use .then(), .fail() at .submit() call to process promise value returned from .then() at validate

function validate() {
  var isFormValid = false;

  var emailValid = false;
  var inputValid = false;
  var passValid = true;

  //VALIDATE EMAIL
  var emailInput = $("input[type='email']");
  // note `return`
  return $.get("/checkEmail", {
    email: emailInput.val()
  })
  .then(function(data) {
    // perform all necessary logic, return `true` or `false` within `.then()`
    if (data.userExists) {
      emailInput.removeClass("valid");
      emailInput.addClass("invalid");
      return false;
    } else {
      emailValid = true;
      emailInput.removeClass("invalid");
      emailInput.addClass("valid");
    }

    if (passValid && emailValid && inputValid) {
      return true;
    }
    /*
      // if below logic is necessary, perform logic within `.then()`

      //ADD VALID CLASS TO INPUTS
      var inputs = $("input,textarea");
      inputs.each(function() {
        if ($(this).val() != "") {
          inputValid = true;
          $(this).removeClass("invalid");
          $(this).addClass("valid");
        } else {
            $(this).removeClass("valid");
            $(this).addClass("invalid");
            return false;
        }
        if (passValid && emailValid && inputValid) {
          return true;
        }
     });

     //VADIDATE PASSWORD
     var pass = $("input[name='password']");
     var repass = $("input[name='repassword']");
     if (pass.val() != repass.val()) {
       passValid = false;
       repass.removeClass("valid");
       repass.addClass("invalid");
       return false;
     }
    */
  });

}

$(document).ready(function() {
  $("#registerForm").submit(function(event) {
    event.preventDefault();
    var elem = event.currentTarget;
    validate()
    .then(function(bool) {
      // if `bool` is `true` call `.submit()`
      if (bool) {
        elem.submit()
      }
    })
    // handle error
    .fail(function(jqxhr, textStatus, errorThrown) {
       console.log(errorThrown)
    })
  });
});

Post a Comment for "Why Is My Function Returning Undefined?"