1
\$\begingroup\$

I'm not a pro in js so, my code is a mess (but it's working!). I would like to ask your help to reduce some redundancies in two cases. Those two are codes are affecting these two forms:

<form action="contact.php" method="post" name="form1" onsubmit="return validateForm1()">
    <input type="text" name="name" id="inputName1" placeholder="Name">
    <input type="text" name="tel" id="inputTel1" placeholder="Telephone Number">
    <input type="text" name="address" id="inputAdr1" placeholder="Address">
    <input type="text" name="topic" id="inputTop1" placeholder="Topic">
    <input type="email" name="email" id="inputMail1" placeholder="E-mail">
    <input type="email" id="inputConfirmMail1" onblur="mailConfirm1()" placeholder="Confirm E-mail">
    <input type="submit" value="Send">
</form>

<form action="contact.php" method="post" name="form2" onsubmit="return validateForm2()">
    <input type="text" name="name" id="inputName2" placeholder="Name">
    <input type="text" name="tel" id="inputTel2" placeholder="Telephone Number">
    <input type="text" name="address" id="inputAdr2" placeholder="Address">
    <input type="text" name="topic" id="inputTop2" placeholder="Topic">
    <input type="email" name="email" id="inputMail2" placeholder="E-mail">
    <input type="email" id="inputConfirmMail2" onblur="mailConfirm2()" placeholder="Confirm E-mail">
    <input type="submit" value="Send">
</form>

FIRST (a function to prevent my two forms to have empty inputs before submission)

function validateForm1() {
    var c = document.forms["form1"]["name"].value;
    var d = document.forms["form1"]["tel"].value;
    var e = document.forms["form1"]["address"].value;
    var f = document.forms["form1"]["topic"].value;
    var g = document.forms["form1"]["email"].value;
    if (c == null || c == "") {
            alert("insert your name");
            return false;
        }
        else if (d == null || d == "") {
            alert("insert your telephone");
            return false;
        }
        else if (e == null || e == "") {
            alert("insert your address");
            return false;
        }
        else if (f == null || f == "") {
            alert("insert a topic");
            return false;
        }
        else if (g == null || g == "") {
            alert("insert your email");
            return false;
        }
    }
    function validateForm2() {
        var c = document.forms["form2"]["name"].value;
        var d = document.forms["form2"]["tel"].value;
        var e = document.forms["form2"]["address"].value;
        var f = document.forms["form2"]["topic"].value;
        var g = document.forms["form2"]["email"].value;
        if (c == null || c == "") {
            alert("insert your name");
            return false;
        }
        else if (d == null || d == "") {
            alert("insert your telephone");
            return false;
        }
        else if (e == null || e == "") {
            alert("insert your address");
            return false;
        }
        else if (f == null || f == "") {
            alert("insert a topic");
            return false;
        }
        else if (g == null || g == "") {
            alert("insert your email");
            return false;
        }
    }

SECOND (I have a "confirm your email" area in my form so I did this function to make sure the user inputs the same value in both areas)

function mailConfirm1() {
    var mail1 = document.getElementById("inputMail1").value;
    var conMail1 = document.getElementById("inputConfirmMail1").value;
    if(mail1 != conMail1) {
        alert('both emails are not the same');
    }
}
function mailConfirm2() {
    var mail2 = document.getElementById("inputMail2").value;
    var conMail2 = document.getElementById("inputConfirmMail2").value;
    if(mail2 != conMail2) {
        alert('both emails are not the same');
    }
}
\$\endgroup\$
  • \$\begingroup\$ Why are there two forms that seem to collect the exact same information? You know you can only post one at a time right (outside of submitting forms via AJAx or similar)? \$\endgroup\$ – Mike Brant Jul 22 '16 at 3:33
  • \$\begingroup\$ Hello @MikeBrant! Yeah, I know AJAX can do this, but the problem is I don't know how to use AJAX so, I have two modals in my page with pretty much the same inputs, but for different subjects. \$\endgroup\$ – Felipe Felix de Luca Jul 22 '16 at 3:46
0
\$\begingroup\$

Two general things:

Avoid variable-names which consist of just one character.

What I mean is: Even something like 'telValue' is better then 'd'. Still not pretty but at least one get an idea what is meant.

You should care about name conflicts.

It would do no harm to attach the functions on to a global object. Or to use a Immediately Invoked Function Expression.

Examples here: https://addyosmani.com/blog/essential-js-namespacing/

Concerning the redundancy issue:

You could data-attributes and class-names. Then using iteration-functions in JavaScript.

Example what I mean here:

(function() {
  document.querySelector('.user-data').addEventListener('submit', function(e) {
    e.preventDefault();

    validateForm(this);
  });

  function validateForm(formElement) {
    var inputs = formElement.querySelectorAll('.not-empty');
    var valid = true;

    inputs = Array.prototype.slice.call(inputs);

    inputs.forEach(function(inputElement) {

      if (!inputElement.value.length) {
        let message = inputElement.dataset.subject || ' the demanded value';

        alert("Please insert " + message + '.');

        if (valid) {
          valid = !valid;
        }
      }
    });

    if (valid) {
      formElement.submit();
    }        
  }
})();
<div class="wrap">
  <form class="user-data" action="contact.php" method="post" name="form1" >
    <input class="not-empty" data-subject="your name" type="text" name="name" id="inputName1" placeholder="Name">
    <input class="not-empty" data-subject="your telephone" type="text" name="tel" id="inputTel1" placeholder="Telephone Number">
    <input class="not-empty" data-subject="your address" type="text" name="address" id="inputAdr1" placeholder="Address">
    <input class="not-empty" data-subject="a topic" type="text" name="topic" id="inputTop1" placeholder="Topic">
    <input class="not-empty" data-subject="your email" type="email" name="email" id="inputMail1" placeholder="E-mail">
    <input class="not-empty" type="email" id="inputConfirmMail1" placeholder="Confirm E-mail">
    <input type="submit" value="Send">
  </form>
</div>

\$\endgroup\$
  • \$\begingroup\$ Thank you very much, @mizech! I'm gonna try it later! Thank you for your explanation on the variables names as well! \$\endgroup\$ – Felipe Felix de Luca Jul 23 '16 at 8:56
  • \$\begingroup\$ @FelipeFelixdeLuca You're welcome. :) Please pay attention: I haven't tested my code very much. If you like the idea then used it for your own project. But better write it from scratch. \$\endgroup\$ – michael.zech Jul 23 '16 at 9:21
2
\$\begingroup\$

The simplest way to minimise your code is to change the functions you've written to accept parameters.

HTML:

<form action="contact.php" method="post" name="form1" 
    onsubmit="return validateForm(this)">
...
<input type="email" name="conEmail" id="inputConfirmMail1" 
    onblur="mailConfirm(this, 'inputMail1')" placeholder="Confirm E-mail">

JS:

function validateForm(form) {
  var c = form.name.value;
  var d = form.tel.value;
  var e = form.address.value;
  var f = form.topic.value;
  var g = form.email.value;

  if (!c) {
     alert("insert your name");
     return false;
  }
  else if (!d) {
     alert("insert your telephone");
     return false;
  }
  else if (!e) {
     alert("insert your address");
     return false;
  }
  else if (!f) {
     alert("insert a topic");
     return false;
  }
  else if (!g) {
     alert("insert your email");
     return false;
  }
}

function mailConfirm(input, target) {
  var mail = document.getElementById(target).value;
  var conMail = this.value;
  if(mail != conMail) {
     alert('both emails are not the same');
  }
}

However this doesn't stop you from submitting the form with both email addresses being different or having never entered the confirmation email.

Also, hand writing out every single validation rule for each individual input would be very time consuming and prone to business logic errors.

I would highly recommend you use an open source validator to assist like Parsley or Bootstrap Validator

\$\endgroup\$
  • \$\begingroup\$ No worries @Felipe, I hope it helps \$\endgroup\$ – Alex Dacre Jul 26 '16 at 23:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.