skip to Main Content

I need to validate the fields below, users can enter 0, but not in both fields, and neither one of the fields can be empty.

I am trying to do this:

if((document.getElementById("NumberOfOpenings").value.trim() == "" || document.getElementById("NumberOfOpenings").value.trim() == 0) && (document.getElementById("NumberOfEntrances").value.trim() == "" || document.getElementById("NumberOfEntrances").value.trim() == 0)) {
// instruct user to only enter 0 in one but not both fields, and make sure field is not left black.
} else {
    // carry on
    }
}

Could I get some basic help on this question? Does the code look correct?

Thank you

5

Answers


  1. Modified version of code that should fix your issues:

    let openingsValue = document.getElementById("NumberOfOpenings").value.trim();
    let entrancesValue = document.getElementById("NumberOfEntrances").value.trim();
    
    if (openingsValue === "" || entrancesValue === "") {
        // Instruct user that neither field can be left empty
    } else if (parseInt(openingsValue, 10) === 0 && parseInt(entrancesValue, 10) === 0) {
        // Instruct user to only enter 0 in one field, but not both fields
    } else {
        // Go on
    }
    
    Login or Signup to reply.
  2. First of all, make the code easier to read by copying the values into variables so you don’t have to keep writing the verbose calls to getElementById().

    Then you can combine the 3 conditions.

    let numOpenings = document.getElementById("NumberOfOpenings").value.trim();
    let numEntrances = document.getElementById("NumberOfEntrances").value.trim();
    
    if (numOpenings === "" || numEntrances === "" || (numOpenings === "0" && numEntrances === "0") {
        // report validation error
    } else {
        // process values
    }
    
    Login or Signup to reply.
  3. Try storing the id´s on variables and using else if

    let numberOfOpeningsValue = document.getElementById("NumberOfOpenings").value.trim();
    let numberOfEntrancesValue = document.getElementById("NumberOfEntrances").value.trim();
    
            if (numberOfOpeningsValue === "" || numberOfOpeningsValue === 0 ) {
            // Logic When numberOfOpeningsValue has an empty value and numberOfOpeningsValue is equal to 0
        } else if (numberOfEntrancesValue === "" || numberOfEntrancesValue === 0) {
           // Logic When numberOfEntrancesValue has an empty value and numberOfEntrancesValue is equal to 0
        }
        else if (numberOfOpeningsValue === "" || numberOfOpeningsValue === 0) {
            // Logic When numberOfOpeningsValue has an empty value and numberOfOpeningsValue is equal to 0
        } else if (numberOfEntrancesValue === "" || numberOfEntrancesValue === 0) {
            // Logic When numberOfEntrancesValue  has an empty value and numberOfEntrancesValue  is equal to 0
        } else {
            // Carry on
        }
    
    Login or Signup to reply.
  4. This question seems to me more like a approach problem rather than JS help. So, Here is a simple easy to understand code (pseudo code almost) where there is a error thrown based on the values entered or not.

    value1 = getRef(1stField); // document.getElementById("NumberOfOpenings").value.trim();
    value2 = getRef(2ndField); // document.getElementById("NumberOfEntrances").value.trim();
    
    function notEmpty(value){
      if(value !== null && value !== undefined)return true;
      return false;
    }
    
    // validate returns true if validated otherwise throws error
    function validate(){
    
      if(notEmpty(value1) && notEmpty(value2)){
        if(value1 == 0 && value2 === 0)throw Error("both can't be zero");
      }else{
        throw Error("Need both values");
      }
    
      return true;
    }
    
    Login or Signup to reply.
  5. You could add in some custom form validation logic.

    Here is an example of a form where either field may be submitted. Since I made the <input> element a [type="number"] input, empty values are not allowed.

    document.forms['CustomForm'].addEventListener('submit', handleSubmit);
    
    function validateForm(form) {
      const errorMessages = {};
      const openingsInput = form.elements.NumberOfOpenings;
      const entrancesInput = form.elements.NumberOfEntrances;
      if (!isValidNumber(openingsInput) && !isValidNumber(entrancesInput)) {
        errorMessages['NumberOfOpenings'] = 'Both fields should not be empty!';
      }
      if (!isNonZero(openingsInput) && !isNonZero(entrancesInput)) {
        errorMessages['NumberOfOpenings'] = 'A zero may only be present in one field!';
      }
      return errorMessages;
    }
    
    function handleSubmit(event) {
      event.preventDefault();
      const form = event.target;
      const openingsInput = form.elements.NumberOfOpenings;
      const errorMessages = validateForm(form);
      for (let field of form.elements) {
        const groupEl = field.closest('.input-group');
        if (!groupEl) {
          continue;
        }
        const errorMessageEl = groupEl.querySelector('.error-message');
        const errorMessage = errorMessages[field.name];
        groupEl.classList.toggle('has-error', errorMessage != null);
        errorMessageEl.textContent = errorMessage ?? '';
      }
      if (Object.keys(errorMessages).length === 0) {
        console.log('Success!');
        //form.submit();
      }
    }
    
    function isValidNumber(numberInput) {
      return !isNaN(numberInput.valueAsNumber);
    }
    
    function isNonZero(numberInput) {
      return numberInput.valueAsNumber !== 0;
    }
    *, *:before, *:after {
      box-sizing: border-box;
    }
    
    html, body {
      width: 100%;
      height: 100%;
      margin: 0;
      padding: 0;
    }
    
    body {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: flex-start;
      padding: 1rem;
    }
    
    .form {
      display: flex;
      flex-direction: column;
      gap: 0.25rem;
    }
    
    .input-group {
      display: grid;
      grid-template-columns: 1fr auto;
      grid-row-gap: 0.5rem;
      grid-column-gap: 1rem;
    }
    
    .input-group:has(input[required]) label:after {
      content: '*';
      color: red;
    }
    
    .input-group.has-error input {
      border-color: red;
    }
    
    .input-group input {
      width: 100%;
    }
    
    .input-group .error-message {
      display: hidden;
      color: red;
      grid-column: 1/3;
    }
    
    .input-group.has-error .error-message {
      display: block;
    }
    <form class="form" name="CustomForm">
      <div class="input-group">
        <label for="no-op">Number of Openings:</label>
        <input type="number" id="no-op" name="NumberOfOpenings" value="0" required />
        <span class="error-message"></span>
      </div>
      <div class="input-group">
        <label for="no-en">Number of Entrances:</label>
        <input type="number" id="no-en" name="NumberOfEntrances" value="0" required />
        <span class="error-message"></span>
      </div>
      <button type="submit">Submit</button>
    </form>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search