简体   繁体   中英

How to Refactor multiple if else statements

I want to do form validation without using these many if else conditions, I want to use single if-else condition is it possible?.

  if($( "#firstname" ).val() == "") {
    $('#dateofbirth').html("Please enter date of birth.");
  }
  else
  {
    $('#dateofbirth').empty();
  }

  if($( "#lastname" ).val() == "") {
    $('#employeetypeid').html("Please select employee type.");
  }
  else
  {
    $('#employeetypeid').empty();
  }
  if($( "#username" ).val() == "") {
    $('#worklocationid').html("Please select work location.");
  }
  else
  {
    $('#worklocationid').empty();
  }
  if($( "#passwordConfirmation" ).val() == "") {
    $('#departmentid').html("Please select organization/dept.");
  }
  else
  {
    $('#passwordConfirmation').empty();
  }`

Based on your example you can collapse all the code into a single function.

for example:

$("form").on("submit", function() {
    checkField("firstname", "dateofbirth", "Please enter date of birth.");
    checkField("lastname", "employeetypeid", "Please select employee type.");
    checkField("username", "worklocationid", "Please select work location.");
    checkField("passwordConfirmation", "departmentid", "Please select organization/dept.");
});


function checkField(fieldToCheck, errorLabel, errorMessage ) {
    if ( $("#" + fieldToCheck).val() == "" ) {
        $("#" + errorLabel).html(errorMessage); 
    }
    else {
        $("#" + errorLabel).empty();
    }
}

I do not really know the syntax, but could you make a separate method which takes a string, a destination, and a probable error message? Something like this:

function getValue(str, field, msg) {
    if($( str ).val() == "") {
        $( field ).html(msg);
    }
    else
    {
        $( field ).empty();
    }
}

And then substitue your code with

getValue("#firstname", '#dateofbirth', "Please enter date of birth.") == "")
getValue("#lastname", '#employeetypeid', "Please select employee type.") == "")
getValue("#username", '#worklocationid', "Please select work location.") == "")
getValue("#passwordConfirmation", '#departmentid', "Please select organization/dept.") == "")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM