5d7c8b8f2de06c07b2bf0848d20ce71f

If three fields (address, zip code and city) have been completed, the AJAX request triggered. The code has determined refactoring potential.

// form fields  
  var address = $("#address");
  var zip = $("#zip");
  var city = $("#city");
  
  function validateAddress() {
    // if it's NOT valid
    if(address.val().length < 1) {
      return false;
    } else {
      return true;
    }
  }
  
  function validateZip() {
    var pattern = new RegExp('[^0-9]+', 'g');
		var zip1 = zip.val().replace(pattern, '');
		zip.val(zip1);
    
    // if is valid
    if(zip.val().length == 5) {
      return true;
    } else {
      return false;
    }
  }
  
  function validateCity() {
    // if it's NOT valid
    if(city.val().length < 1) {
      return false;
    } else {
      return true;
    }
  }
  
  // Show indicator
  function showIndicator() {
    $("img#indicator").show();
  }
  
  // Hide indicator
  function hideIndicator() {
    $("img#indicator").hide();
  }
  
  function validateFields() {
    if(validateAddress() && validateZip() && validateCity()) {
      // Show indicator
      showIndicator();
      
      var req = $("form#new").serialize();
      $.ajax({
        type: "POST",
        url: "checkDuplicate/",
        data: req,
        complete: hideIndicator
      });
    }
  }
  
  // On blur
  $("#address,#zip,#city").blur(function() {
    validateFields();
  });

Refactorings

No refactoring yet !

23132e1aa8457e11b243a43b578d51dc

Simo Niemelä

February 16, 2009, February 16, 2009 09:52, permalink

No rating. Login to rate!
// form fields  
var address = $("#address");
var zip = $("#zip");
var city = $("#city");

function validateAddress() {
  return (address.val().length > 1);
}

function validateZip() {
  var pattern = new RegExp('[^0-9]+', 'g');
	var zipReplaced = zip.val().replace(pattern, '');
	zip.val(zipReplaced);
	
  return (zip.val().length == 5);
}

function validateCity() {
  return (city.val().length > 1);
}

// Show indicator
function showIndicator() {
  $("img#indicator").show();
}

// Hide indicator
function hideIndicator() {
  $("img#indicator").hide();
}

function validateFields() {
  return (validateAddress() && validateZip() && validateCity());
}

// On blur
$("#address,#zip,#city").blur(function() {
  if (validateFields()) {
    // Show indicator
    showIndicator();

    var req = $("form#new").serialize();
    $.ajax({
      type: "POST",
      url: "checkDuplicate/",
      data: req,
      complete: hideIndicator
    });
  }
});

Your refactoring





Format Copy from initial code

or Cancel