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();
}`
最佳答案
根据您的示例,您可以将所有代码折叠到一个函数中。
例如:
$("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();
}
}
关于javascript - 如何重构多个 if else 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44157570/