Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript Multiple validation error message failed

I am unable to figure where is the issue on the javascript, I want show and hide the error message based on the field values is empty or not,
Please find the my javascript code,

if (info == "" && hrContacts == "") {
        document.getElementById("hr_contacts_error").style.display = "block";
        document.getElementById("info_error").style.display = "block";
        return false;
    }else if (hrContacts == "") {
        document.getElementById("hr_contacts_error").style.display = "block";
        return false;
    }else if (hrContacts != "") {
        document.getElementById("hr_contacts_error").style.display = "none";
    }else if (info == "") {
        document.getElementById("info_error").style.display = "block";
        return false;
    }else if (info != "") {
        document.getElementById("info_error").style.display = "none";
    }else if (info != "" && hrContacts != "") {
      form submit
     
    }

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You can simplify this a lot.

  1. First, set the initial state, assume there are no errors, and hide all messages.
  2. Check every individual field, and if there’s an input error, display the message, and set the error tracking boolean to true.
  3. If at the end, there are any errors, return false to prevent form submit.
  4. Actually submit the form, if there’s no errors.
let hasError = false;
document.getElementById("hr_contacts_error").style.display = "none";
document.getElementById("info_error").style.display = "none";

if (hrContacts == "") {
  document.getElementById("hr_contacts_error").style.display = "block";
  hasError = true;
}
if (info == "") {
  document.getElementById("info_error").style.display = "block";
  hasError = true;
}

if (hasError) {
  return false;
}

// form submit

You could reduce some code duplication like this:

let hasError = false;

// Loop over all fields with their error message ID.
[
    [hrContacts, 'hr_contacts_error'],
    [info, 'info_error']
].forEach(([value, errorId]) => {
    const isEmpty = value == '';
    document.getElementById(errorId).style.display = isEmpty ? 'block' : 'none';
    hasError = hasError || isEmpty;
});

if (hasError) {
    return false;
}

// form submit
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading