My Javascript form validation Hello today after few weeks of learning I tried some form validation.
I am wondering how I could improve my code and what things I missed.
Here is a preview hosted on github + repository.
And here is my code :
HTML
&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;en&quot;&gt;
  &lt;head&gt;
    &lt;meta charset=&quot;utf-8&quot;&gt;
    &lt;link rel=&quot;stylesheet&quot; href=&quot;main.css&quot;&gt;
    &lt;link href=&quot;https://fonts.googleapis.com/css2?family=Rubik:wght@300;400;500;600;700&amp;display=swap&quot; rel=&quot;stylesheet&quot;&gt;
    &lt;title&gt;Form validation&lt;/title&gt;
  &lt;/head&gt;
  &lt;body&gt;
    &lt;form action=&quot;#&quot; class=&quot;form&quot;&gt;
      &lt;h2&gt;Contact with us&lt;/h2&gt;
      &lt;div class=&quot;wrapper&quot;&gt;
        &lt;div&gt;
          &lt;input type=&quot;text&quot; name=&quot;name&quot; class='input-name' id='input' placeholder=&quot;First name *&quot; required&gt;
          &lt;p id='input-name-p' class='p-hidden'&gt;&lt;/p&gt;
        &lt;/div&gt;

        &lt;div&gt;
          &lt;input type=&quot;text&quot; name=&quot;surname&quot; class='input-surname' id='input' placeholder=&quot;Surname&quot;&gt;
          &lt;p  id='input-surname-p' class='p-hidden'&gt;&lt;/p&gt;
        &lt;/div&gt;

        &lt;div&gt;
          &lt;input type=&quot;text&quot; name=&quot;email&quot; class='input-email' id='input' placeholder=&quot;E-mail *&quot; required&gt;
          &lt;p id='input-email-p' class='p-hidden'&gt;&lt;/p&gt;
        &lt;/div&gt;

        &lt;div&gt;
          &lt;input type=&quot;text&quot; name=&quot;phone&quot; class='input-phone' id='input' placeholder=&quot;Phone number&quot;&gt;
          &lt;p  id='input-phone-p' class='p-hidden'&gt;&lt;/p&gt;
        &lt;/div&gt;

        &lt;textarea name=&quot;message&quot; rows=&quot;8&quot; cols=&quot;80&quot; class='input-message' id='input' placeholder=&quot;Message *&quot; required&gt;&lt;/textarea&gt;
        &lt;button href=&quot;#&quot; class=&quot;btn&quot;&gt;Submit&lt;/button&gt;
      &lt;/div&gt;
    &lt;/form&gt;

    &lt;script type=&quot;text/javascript&quot; src=&quot;script.js&quot;&gt;
    &lt;/script&gt;

  &lt;/body&gt;
&lt;/html&gt;

JS
'use strict';

const submit = document.querySelector('.btn');
const name = document.querySelector('.input-name');
const surname = document.querySelector('.input-surname');
const email = document.querySelector('.input-email');
const phone = document.querySelector('.input-phone');
const items = document.querySelectorAll('#input');


const isValid = function(item) {
  for (let i = 0; i &lt; item.length; i++) {
    if (item[i].value){ // Check if contains value

      let error = document.getElementById(`${item[i].className}-p`);
      const letters = /^[A-Za-z]+$/;
      const numbers = /^\d+$/;
      let inputLength = item[i].value.length;

      switch (item[i].className){
        case 'input-name':
        case 'input-surname':   
          if(!letters.test(item[i].value)){ // Invalid input 
            error.textContent = 'Invalid data';
            error.classList.remove('p-hidden');
          }else
          error.classList.add('p-hidden');
          break;

        case 'input-email':
          if(!item[i].value.includes('.') || !item[i].value.includes('@') || !letters.test(item[i].value[inputLength-1])  ){ // check if includes (@ or .) and check if the last index is a letter
            error.textContent = 'Invalid data';
            error.classList.remove('p-hidden');
          }else
          error.classList.add('p-hidden');
          break;
        case 'input-phone':
          if(!numbers.test(item[i].value) ||  inputLength&lt;5){  // Invalid input 
            error.textContent = 'Invalid data';
            error.classList.remove('p-hidden');
          }else
          error.classList.add('p-hidden');
          break;
      }

    }
  }
}

for (let i = 0; i &lt; items.length; i++) {
    items[i].addEventListener('click',function(){
      // Check if the input is valid
      isValid(items);
    });
}
Duplicate IDs are invalid HTML You have multiple elements of id='input', which is not permitted in HTML. If multiple elements need a particular attribute, use classes instead. IDs should be reserved for elements that are going to be absolutely unique on a page (or, you could also consider not using IDs at all, since they implicitly create global variables, which can lead to hard-to-understand bugs).
Input iteration You put the input collection into a variable named items, which is good: const items = document.querySelectorAll('#input'); but then you pass the collection to a function whose parameter is named item, and you do:
for (let i = 0; i &lt; item.length; i++) {
  if (item[i].value) { // Check if contains value
    // a long block
  }


A reader of the code wouldn't expect an individual item to have a length and a numeric index. How about calling the parameter items instead - or, even better, inputs?

Rather than iterate over the indicies of each element, since you don't actually care about the indicies, but only about the underlying elements, it might be preferable to use for..of instead, so you never have to reference the indicies.

Nested indentation can be difficult to read. Instead of a long block inside an if statement, consider continuing the loop early instead:


for (const input of inputs) {
  if (!input.value) {
    continue;
  }
  // put validation code here

Or put it into a function:
for (const input of inputs) {
  if (input.value) {
    validateInput(input);
  }

Check validity on blur, not on click. Your current implementation will show errors only after the user has inputted something invalid, focused away, then clicked on the input box again. Better to inform them immediately, as soon as a box is de-focused.
Check validity even if input is empty, since errors may be displayed - if the input is empty, you'll want to clear the error. You could also consider clearing errors when an input is focused (so that errors are only displayed when an input currently isn't active).
Error text is always the same, so don't set it via the JS - put it into the HTML, and hide the error on pageload.
Use the case-insensitive flag in regular expressions instead of repeating both the capital and lowercase versions, eg: /^[a-z]$/i
Wording Contact with us would be better as Contact us
DRY input navigation There are a few sources of repetitiveness in the code:

Separate class names for each input, requiring iteration through each class name in the switch
Separate error class names for each input
Separate logic for each class name

You can make this better by:

Use an object indexed by the name attribute of each input, whose values are regular expressions to test the values against
Navigate to the input's adjacent error element with nextElementSibling instead of having separate error classes

For the email, you can use a regular expression so that the validation is of the same shape as for the other inputs.
const validators = {
  name: /^[a-z]$/i,
  surname: /^[a-z]$/i,
  email: /^(?:[a-z0-9!#$%&amp;'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&amp;'*+/=?^_`{|}~-]+)*|&quot;(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*&quot;)@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9]))\.){3}(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9])|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])$/,
  phone: /^\d{5,}$/,
};
for (const input of document.querySelectorAll('#input')) {
  input.addEventListener('blur', () =&gt; {
    checkValidity(input);
  });
}
const checkValidity = (input) =&gt; {
  const isBad = validators[input.name].test(input.value);
  input.nextElementSibling.classList.toggle('p-hidden', isBad);
};

That's all you need.


'use strict';

const validators = {
  name: /^[a-z]+$/i,
  surname: /^[a-z]+$/i,
  email: /^(?:[a-z0-9!#$%&amp;'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&amp;'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9]))\.){3}(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9])|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])$/,
  phone: /^\d{5,}$/,
};
for (const input of document.querySelectorAll('.wrapper input')) {
  input.addEventListener('blur', () =&gt; {
    checkValidity(input);
  });
}
const checkValidity = (input) =&gt; {
  const isBad = validators[input.name].test(input.value);
  input.nextElementSibling.classList.toggle('p-hidden', isBad);
};
.p-hidden {
  display: none;
}
&lt;form action="#" class="form"&gt;
  &lt;h2&gt;Contact us&lt;/h2&gt;
  &lt;div class="wrapper"&gt;
    &lt;div&gt;
      &lt;input name="name" placeholder="First name *" required&gt;
      &lt;p class='p-hidden'&gt;Invalid data&lt;/p&gt;
    &lt;/div&gt;

    &lt;div&gt;
      &lt;input name="surname" placeholder="Surname"&gt;
      &lt;p class='p-hidden'&gt;Invalid data&lt;/p&gt;
    &lt;/div&gt;

    &lt;div&gt;
      &lt;input name="email" placeholder="E-mail *" required&gt;
      &lt;p class='p-hidden'&gt;Invalid data&lt;/p&gt;
    &lt;/div&gt;

    &lt;div&gt;
      &lt;input name="phone" placeholder="Phone number"&gt;
      &lt;p class='p-hidden'&gt;Invalid data&lt;/p&gt;
    &lt;/div&gt;

    &lt;textarea name="message" rows="8" cols="80" placeholder="Message *" required&gt;&lt;/textarea&gt;
    &lt;button href="#" class="btn"&gt;Submit&lt;/button&gt;
  &lt;/div&gt;
&lt;/form&gt;



The email regex is probably more complicated than it needs to be, you could write a much more easy-to-read one with only a handful of characters that works just as well in 99% of situations, if you wanted.
Another option would be to remove all the JavaScript, and use the pattern attribute and type=&quot;email&quot; in the HTML instead, letting the browser inform the user of invalid inputs:


&lt;form action="#" class="form"&gt;
  &lt;h2&gt;Contact us&lt;/h2&gt;
  &lt;div class="wrapper"&gt;
    &lt;div&gt;
      &lt;input name="name" placeholder="First name *" required pattern="[a-zA-z]+"&gt;
    &lt;/div&gt;
    &lt;div&gt;
      &lt;input name="surname" placeholder="Surname" pattern="[a-zA-z]+"&gt;
    &lt;/div&gt;
    &lt;div&gt;
      &lt;input name="email" placeholder="E-mail *" required type="email"&gt;
    &lt;/div&gt;
    &lt;div&gt;
      &lt;input name="phone" placeholder="Phone number" pattern="\d+{5,}"&gt;
    &lt;/div&gt;

    &lt;textarea name="message" rows="8" cols="80" placeholder="Message *" required&gt;&lt;/textarea&gt;
    &lt;button href="#" class="btn"&gt;Submit&lt;/button&gt;
  &lt;/div&gt;
&lt;/form&gt;



Result: