5

I am trying to validate a large contact form. When the user forgets a required input field then I populate the empty variable with default text.

My current solution uses nine if statements. Is there a better way to do it with less code?

html: <xehases class="" id="xehases"></xehases>

var onoma = $("#fname").val();
var eponimo = $("#lname").val();
var email = $("#email").val();
var diefthinsi = $("#address").val();
var poli = $("#city").val();
var xora = $("#country").val();
var katigoriaDiafimisis = $("#AdCategory").val();
var plano = $("#plan").val();
var istoselida = $("#website").val();
var epixirisi = $("#company").val();
var minima = $("#message").val();

var missing = '  ';

if (onoma === "") {
  missing += 'Όνομα ';
  $("xehases#xehases").html(missing);
} else {
  $("xehases#xehases").html(missing);
}

if (eponimo === "") {
  missing += 'Επώνυμο ';
  $("xehases#xehases").html(missing);
} else {
  $("xehases#xehases").html(missing);
}

if (email === "") {
  missing += 'email ';
  $("xehases#xehases").html(missing);
} else {
  $("xehases#xehases").html(missing);
}

if (poli === "") {
  missing += 'Πόλη ';
  $("xehases#xehases").html(missing);
} else {
  $("xehases#xehases").html(missing);
}

if (xora === "please choose a category") {
  missing += 'Χώρα ';
  $("xehases#xehases").html(missing);
} else {
  $("xehases#xehases").html(missing);
}

if (plano === "") {
  missing += 'Πλάνο ';
  $("xehases#xehases").html(missing);
} else {
  $("xehases#xehases").html(missing);
}

if (katigoriaDiafimisis === "") {
  missing += 'Κατηγορία Διαφήμισης ';
  $("xehases#xehases").html(missing);
} else {
  $("xehases#xehases").html(missing);
}

if (epixirisi === "") {
  missing += 'Επιχείρηση ';
  $("xehases#xehases").html(missing);
} else {
  $("xehases#xehases").html(missing);
}

if (minima === "") {
  missing += 'Μήνυμα ';
  $("xehases#xehases").html(missing);
} else {
  $("xehases#xehases").html(missing);
}
  • There is one extra `else{//proceed to ajax}` which is not bound to any `if` – brk Sep 03 '17 at 07:19
  • it shouldn't matter if it is an html tag or not. I created it my own just to remember. –  Sep 03 '17 at 07:41
  • I would also recommend using english in your code for everything (variables, comments...), even if it is just your small hobby project (to get into the habit). If it is work related, then definitely use english, even if you and all your colleagues speak only greek. You never know who will come after you to maintain it. – Lope Sep 03 '17 at 10:49

3 Answers3

11

You can create a dict containing the form fields and the strings displayed when they are missing and iterate over the list. Also, as another response indicated, move setting the missing error message to the end and only do it once; Further, the if/else for that isn't needed if you're going to do the same thing in each case. Write the code similar to this:

// key is form input, value is displayed in missing field message
const fieldsDict = {
    "fname": "Όνομα",
    "lname": "eponimo",
    // ...
};

let missing = "";

Object.keys(fieldsDict).forEach((field) => {
    if ($("#" + field).val() === "") {
        missing += fieldsDict[field] + " ";
    }
});

$("xehases#xehases").html(missing);
Jared Sohn
  • 443
  • 5
  • 17
  • const fieldsDict is javascript? –  Sep 03 '17 at 07:36
  • 1
    @Eternal [yes it is](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const) – adiga Sep 03 '17 at 07:37
  • Yeah, I'll add a comment before that. – Jared Sohn Sep 03 '17 at 07:38
  • so where should I add "name is missing" or "last name missing" –  Sep 03 '17 at 07:40
  • Change the line that starts with `missing += fieldsDict` to include text beyond just the field name. – Jared Sohn Sep 03 '17 at 07:42
  • 2
    @JaredSohn the key value pair should be reversed like this: `const fieldsDict = { "fname": "Όνομα",..` – adiga Sep 03 '17 at 07:42
  • @adiga yes you are correct it wasn't working without reversing these –  Sep 03 '17 at 07:48
  • can I add a comma if there are more than 1 empty fields? Like `name,lastname` and not if it is only 1 like `name is missing,` –  Sep 03 '17 at 07:51
  • I'd suggest appending the missing fields to an array instead of building a string and then doing an `array.join` with a comma at the end (as suggested as an answer to https://stackoverflow.com/questions/201724/easy-way-to-turn-javascript-array-into-comma-separated-list) So set missing to [] instead of "", do missing.push(fieldsDict[field]) within the forEach, and then do missing.join(", ") when setting the output. – Jared Sohn Sep 03 '17 at 07:53
  • i have a dropdown where i have to check if the value is "please choose a category" How can i check that for the variable `xora` see my updated question, you'll understand –  Sep 03 '17 at 08:02
  • change the if statement to this: `$("#" + field).val() === '' || $("#" + field).val() === 'please choose a category'` – csandreas1 Sep 03 '17 at 18:50
1

I can see there is some duplication of the code example

          $("xehases#xehases").html(missing);

This can be put only in the last. So over all you just need to build the content of missing variable.

         if(onoma === "")
             missing +='Όνομα ';
         if(eponimo === "")
             missing+='Επώνυμο ';   
         if(email === "")
            missing+='email ';
         if(poli === "")
            missing+='Πόλη ';
         if(xora === ""){
           missing+='Χώρα ';  
          // and more               
          $("xehases#xehases").html(missing);
Devesh
  • 4,500
  • 1
  • 17
  • 28
  • @Eternal I have updated my answer with the code , please have a look if I get it right... – Devesh Sep 03 '17 at 07:26
  • you forgot the else on each if. You have to clear the variable if nothing is empy –  Sep 03 '17 at 07:29
  • @Eternal The variable is empty to start with, and a list of the missing fields is being created inside it. –  Sep 03 '17 at 07:31
0

Something like this...

var fields = ['fname', 'lname', 'email']; // ...and so on
var errField = $('#xehases');

function submit(){
    fields.forEach(function(field){
        var domElem = $('#' + field);
        if (domElem.val() === '') {
            errField.html(errField.text() + ' ' + domElem.attr('err-msg'));
        }
    });
}

'err-msg' could be an attribute on input elem used for missing msg.