0

I am still in the process of learning JavaScript but attempting to build in some form validation for some end users so that fields cannot be empty based on certain variables.

Here is my relevant code.

function validateForm() {
  var a = document.forms["myForm"]["Joint_1"].value;
  var b = document.forms["myForm"]["ID_1"].value;
  var c = document.forms["myForm"]["ID_2"].value;
  if (a == "Y" && b == "" && c == "") {
    console.log("Account is indicated to be joint, either one or both instances of ID is incomplete");
    return false;
  }
  if (a == "N" && b == "") {
    console.log("ID is incomplete for a single owner");
    return false;
  }
}
.a {
  display: table-row;
}

.a div {
  display: table-cell;
  padding: 5px;
}
<form name="myForm" onsubmit="return validateForm()" method="post">
  <div class="a">
    <div class='a'>
      <div>Joint Account?:</div>
      <div><select id="unit" size="1" name="Joint_1">
        <option disabled="disabled" selected="selected" value=""></option>
        <option value="Y">Y</option>
        <option value="N">N</option>
        </select></div>
    </div>
  </div>
  <div class="a">
    <div>ID:</div>
    <div><input type="text" name="ID_1" size="12" maxlength="12"></div>
  </div>
  <div class="a">
    <div>ID:</div>
    <div><input type="text" name="ID_2" size="12" maxlength="12"></div>
  </div>
  <div class='a'>
    <div><input type="submit" value="Save"></div>
    <div> <input type="reset" value="Reset"></div>
  </div>
</form>

Joint_1 will never be an empty string as it will be inheriting its value from elsewhere.

The form works when Joint_1 == "Y" and both ID_1 == "" and ID_2 == "".

However, when Joint_1 == "Y" and either ID_1 or ID_2 is not an empty string, the form will advance instead of generating the alert. Both ID_1 and ID_2 must be filled out in the instance of a "Y" value in Joint_1.

Is there a way to accomplish this so that the alert will generate when Joint_1 == "Y" and either ID_1 == "" or ID_2 == ""? I tried using the or (||) operator instead, but then I failed on the Joint_1 == "N" logic.

Paul Roub
  • 36,322
  • 27
  • 84
  • 93
FFF
  • 3
  • 2

1 Answers1

0
function validateForm() {
  var a = document.forms["myForm"]["Joint_1"].value,
      b = document.forms["myForm"]["ID_1"].value,
      c = document.forms["myForm"]["ID_2"].value;

  if (a === "Y" && (b === "" || c === "")) {
    alert("Account is indicated to be joint, either one or both instances of ID is incomplete");
    return false;
  } else if (a === "N" && b === "") {
    alert("ID is incomplete for a single owner");
    return false;
  }
}  

As a best practice you might want to consider using ===(identity) instead of ==(equality) for comparison - read on subject.

Community
  • 1
  • 1
Zoltan Toth
  • 46,981
  • 12
  • 120
  • 134
  • Thank you! That worked for what I was attempting to accomplish. As I said, I'm still learning. I appreciate all the help I can get at this stage! – FFF May 01 '17 at 21:06