Javascript function returns undefined as it should not be

I have function check dynamic input fields with a certain class. Those fields takes email address so checking if it is a valid email address.

There could be many email field, if one of them fails against email address test, it should return FALSE, else it should return TRUE. Finally when submit clicked save_form() runs. If it get false, it should stop, otherwise continue. But it gets "undefined" always.

Here is what I have:

function validate_email_string(email_address) {
  var emailReg=/^([\w-\.][email protected]([\w-]+\.)+[\w-]{2,4})?$/;
  var emailTest = emailReg.test(email_address);
  var result = (emailTest === false) ? false : true;
  return result;
}

function validate_email_extensions(email_field_selector, message) {
  var invalid_message = null;
  if (typeof message !== "undefined") {
    invalid_message = message;
  } else {
    invalid_message = '<?=lang("i18n_invalid_email_address");?>';
  }
  var email_fields_length = $(email_field_selector).length;
  var is_valid = true;
  if (email_fields_length) {
    $(email_field_selector).each(function(index, el) {
      if($(el).val()) {
        if(!validate_email_string($(el).val())) {
          is_valid = false;
        }
        if (index === email_fields_length - 1) {
          if (is_valid === false) {
            Interact.show(invalid_message);
          }
          return is_valid;
        }
      } else {
        if (index === email_fields_length - 1) {
          if (is_valid === false) {
            Interact.show(invalid_message);
          }
          return is_valid;
        }
      }
    });
  } else {
    return is_valid;
  }
}

function save_form() {
    var emails = validate_email_extensions('.jq-extension-email');
    if(!emails){return false}
    ....

But validate_email_extensions function returns undefined. I put console.log() everywhere, probably it's blind of me but any help is quite appreciated.

Answers 1

  • Your returns are from your loop to validate_email_extensions, not from validate_email_extensions to save_form as you're expecting.

    validate_email_extensions needs to return the value to save_form still.

    The only time where your function is correctly returning a value is when this case is FALSE

    if (email_fields_length) {
    

    It returns no value when control goes in that if condition.


Related Articles