简体   繁体   English

如何重构多个if else语句

[英]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-else条件吗?

  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.") == "")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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