我想在不使用这些其他条件的情况下进行表单验证,我想使用单个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();
  }`

最佳答案

根据您的示例,您可以将所有代码折叠到一个函数中。

例如:

$("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();
    }
}

07-24 09:31