How to make a custom validation for a form using javascript?

so i need to make validation for a form. the form need to have the value of 1 – 6 and there cannot be a duplicate.

so i make a temporary variable to record all the data kind of like this

let temporary = []

temporary[document.getElementById('needs_1').value-1] = 'needs 1';
temporary[document.getElementById('needs_2').value-1] = 'needs 2';
temporary[document.getElementById('needs_3').value-1] = 'needs 3';
temporary[document.getElementById('needs_4').value-1] = 'needs 4';
temporary[document.getElementById('needs_5').value-1] = 'needs 5';
temporary[document.getElementById('needs_6').value-1] = 'needs 6';

to validate it i put a condition with the length of the array is equal to 6. that will validate the 1-6 value needed. but it cannot validate duplicate number. because if there is skipped number lets say 1,5,6 if i check the length of temporary variable it still result in 6

>Solution :

You can try the following way:

<form id="myForm">
  <input type="text" id="txt_1"><br>
  <input type="text" id="txt_2"><br>
  <input type="text" id="txt_3"><br>
  <input type="text" id="txt_4"><br>
  <input type="text" id="txt_5"><br>
  <input type="text" id="txt_6"><br>
  <input type="submit" value="Submit">
</form>

<script>
document.getElementById("myForm").onsubmit = function(event) {
  event.preventDefault(); //prevent the form from submitting

  let temporary = [];

  for (let i = 1; i <= 6; i++) {
    let inputValue = parseInt(document.getElementById(`txt_${i}`).value);

    if (!isNaN(inputValue) && inputValue >= 1 && inputValue <= 6) {
      if (temporary.includes(inputValue)) {
        alert(`Duplicate value: ${inputValue}`);
        return; //exit the function
      } else {
        temporary.push(inputValue);
      }
    } else {
      alert(`Invalid value: ${inputValue}`);
      return; //exit the function
    }
  }
  //check if you have exactly 6 values
  if (temporary.length === 6) {
    alert("Form is valid.");
    //submit the form 
  } else {
    alert("Form is invalid.");
  }
}
</script>

Leave a Reply