Reputation: 171
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();
}`
Upvotes: 0
Views: 1112
Reputation: 320
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.") == "")
Upvotes: 0
Reputation: 15968
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();
}
}
Upvotes: 3