Paul Davis
Paul Davis

Reputation: 525

Form Validation - multiple inputs with same class

I am trying to validate inputs. On this particular page, I have 5 inputs. Three will be selected and all three require numbers. Just for this case, I am only going to check that the user has input a number (there will be more things to validate, but I want to get this right first so I don't repeat myself on multiple pages).

const formE = document.getElementById("SubmissionForm");
const sE = document.getElementById("input1");
const tE = document.getElementById("input2");

formE.addEventListener("click", validate);
function validate(e) {
  e.preventDefault();

  let valid = true;

  if (!sE.value) {
    const sError = document.querySelector("showError");
    sError.forEach((showError));
    sError.setAttribute("aria-hidden", false);
    sError.setAttribute("aria-invalid", true);
  }
  return valid;
}

Now, I am aware this doesn't work with this (I got stuck thinking about a forEach and I just haven't taken it further yet.

In the HTML under the input I have this:

<span role="alert" class="showError" aria-hidden="true"> Please enter a number </span>

Bear in mind, this is just for the number validation I will add other validation points too.

So - what is the correct syntax for the JS to find all the showError classes and make their become visible when the user doesn't put in a number?

Upvotes: 0

Views: 560

Answers (1)

Emre
Emre

Reputation: 840

There are a lot of ways for that. Basically I can suggest this solution relevant to your question:

const button = document.querySelector('#button');
const number_1 = document.querySelector('#number_1');
const number_2 = document.querySelector('#number_2');
const error = document.querySelector('#error');

button.addEventListener('click',()=>{
    if(isNaN(parseInt(number_1.value)) || isNaN(parseInt(number_2.value))){
        error.removeAttribute('hidden');
    }else{
        error.setAttribute('hidden','');
    }
});
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Validation Demo</title>
</head>
<body>
    <input type="text" id="number_1">
    <input type="text" id="number_2">
    <button id="button">Check them!</button>
    <p id="error" hidden>You can type only numbers!</p>
</body>
</html>

Upvotes: 1

Related Questions