Home > Enterprise >  JavaScript, can't remove css class
JavaScript, can't remove css class

Time:01-28

I did validation for html form in js, it contains two actions 1st is checking data from inputs after click on "send" button and display errors from array below form - here everything is ok.

Second part of validation is checking fields during data input. When data don't match to the key(regex) or condition , then appears red outline round field.

Here I've got a problem it works only for my three of five fields, work for name(Imie i Naziwsko), email(Adres mailowy) and phone(Telefon).

For title(Tytul) and message(wiadomosc) it shows me red outline when data is wrong but it's not removed when data is correct.

I don't have any errors at console.

JsFiddle

const formChecker = () => {
  //get elements
  const contactForm = document.getElementById("form-contact");
  const inputName = document.getElementById("name");
  const inputEmail = document.getElementById("mailadress");
  const inputTitle = document.getElementById("title");
  const inputMessage = document.getElementById("message");
  const inputPhone = document.getElementById("phone-number");
  const divError = document.querySelector(".error-message");

  //regex patterns
  const regexPatternMail =
    /^([^\x00-\x20\x22\x28\x29\x2c\x2e\x3a-\x3c\x3e\x40\x5b-\x5d\x7f-\xff] |\x22([^\x0d\x22\x5c\x80-\xff]|\x5c[\x00-\x7f])*\x22)(\x2e([^\x00-\x20\x22\x28\x29\x2c\x2e\x3a-\x3c\x3e\x40\x5b-\x5d\x7f-\xff] |\x22([^\x0d\x22\x5c\x80-\xff]|\x5c[\x00-\x7f])*\x22))*\x40([^\x00-\x20\x22\x28\x29\x2c\x2e\x3a-\x3c\x3e\x40\x5b-\x5d\x7f-\xff] |\x5b([^\x0d\x5b-\x5d\x80-\xff]|\x5c[\x00-\x7f])*\x5d)(\x2e([^\x00-\x20\x22\x28\x29\x2c\x2e\x3a-\x3c\x3e\x40\x5b-\x5d\x7f-\xff] |\x5b([^\x0d\x5b-\x5d\x80-\xff]|\x5c[\x00-\x7f])*\x5d))*(\.\w{2,}) $/;

  const regexPattern =
    /^([A-ZŻŹĆĄŚĘŁÓŃ][a-zżźćńółęąś{3,}] )(\s|-|_) ([A-ZŻŹĆĄŚĘŁÓŃ][a-zżźćńółęąś{3,}] )$/;
  const regexPhonePattern =
    /^[ ]?\d{1,3}\s?(-)?[0-9]{3}(\s)?[0-9]{3,4}(\s)?[0-9]{3}(\s)?$/;

  const regexTitltePattern = / (\w{3,30}) /;

  //remove html validation
  contactForm.setAttribute("novalidate", true);

  //test functions
  function testText(field) {
    return regexPattern.test(field.value);
  }

  function testMail(field) {
    return regexPatternMail.test(field.value);
  }

  function testPhone(field) {
    return regexPhonePattern.test(field.value);
  }

  function testTitle(field, lng) {
    return regexTitltePattern.test(field.value);
  }

  function testMessage(field, lng) {
    return field.value.length < lng;
  }

  //add and remove red stroke
  function markFieldAsError(field, show) {
    if (show) {
      field.classList.add("invalid");
    } else {
      field.classList.remove("invalid");
    }
  }

  //add listener
  inputName.addEventListener("input", (e) =>
    markFieldAsError(e.target, !testText(e.target))
  );
  inputEmail.addEventListener("input", (e) =>
    markFieldAsError(e.target, !testMail(e.target))
  );
  inputPhone.addEventListener("input", (e) =>
    markFieldAsError(e.target, !testPhone(e.target))
  );
  inputTitle.addEventListener("input", (e) =>
    markFieldAsError(e.target, !testTitle(e.target))
  );
  inputMessage.addEventListener("input", (e) =>
    markFieldAsError(e.target, !testMessage(e.target))
  );

  //send
  contactForm.addEventListener("submit", (el) => {
    el.preventDefault();
    let formErrors = [];

    //hide error - red stroke
    for (const el of [
      inputName,
      inputEmail,
      inputPhone,
      inputTitle,
      inputMessage,
    ]) {
      el.markFieldAsError(el, false);
    }

    if (!testText(inputName)) {
      formErrors.push("Proszę poprawnie wypłenić  pole Imię i Nazwisko ");
      markFieldAsError(inputName, true);
    }

    if (!testMail(inputEmail)) {
      formErrors.push("Proszę poprawnie wypełnić pole z adresem email");
      markFieldAsError(inputEmail, true);
    }

    if (!testPhone(inputPhone)) {
      markFieldAsError(inputPhone, true);
    }

    if (!testTitle(inputTitle)) {
      formErrors.push("Pole wiadomość musi zawierać minimum 3 znaki");
      markFieldAsError(inputTitle, true);
    }

    if ((!testMessage(inputMessage), 10)) {
      formErrors.push("Pole wiadomość musi zawierać minimum 10 znaków");
      markFieldAsError(inputMessage, true);
    }

    if (!formErrors.length) {
      //if no errors send form
      el.target.submit();
    } else {
      //if there are some errors

      divError.innerHTML = `<h3 >Przed wysłaniem proszę poprawić błędy:</h3>
                    <ul >
                        ${formErrors.map((el) => `<li>${el}</li>`).join("")} 
                    </ul>`;
    }
  });
};

formChecker();
body {
  background-color:#412f28;
  display:flex;
  align-items:center;
  flex-direction:column;
}
#form p {
  font-size: 1rem;
  color:white!important;
}
#form .star {
  font-size: 1rem;
  vertical-align: super;
  color:#E3A324!important;
}
/* Style inputs with type="text", select elements and textareas */
input[type=text], input[type=mail],
select, textarea {
  width: 100%; /* Full width */
  padding: 24px; /* Some padding */ 
  border: 1px solid #35251f; /* Gray border */
  border-radius: 4px; /* Rounded borders */
  box-sizing: border-box; /* Make sure that padding and width stays in place */
  margin-top: 6px; /* Add a top margin */
  margin-bottom: 16px; /* Bottom margin */
  resize: vertical /* Allow the user to vertically resize the textarea (not horizontally) */
}
/*
.invalid {
border: 4px solid red;
outline: 4px;
box-shadow: 0 0 2px red;
}
*/
.invalid {
  border:0px!important ;
  transition: border .3s linear;
  outline: dashed 1px red!important;
  outline-width:1px;
  outline-offset: 4px;
  transition: border, outline .3 ease-out;
}
/* Style the submit button with a specific background color etc */
input[type=submit], .custom-file-upload  {
  background-color:#E3A324;
  color: white;
  font-weight: 700;
  padding: 12px 30px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  margin-left: 5px;
  margin-right: 5px;
  transition: background-color 1s linear;
}
input[type="text"], input[type="mail"], textarea {
  border:2px solid #cc9933;
  outline:0;
  transition: border .3s linear;
  outline: 0px;
}
input[type="text"]:hover , input[type="mail"]:hover  {
  border: 2px solid #ffaa00;
}
input[type="file"] {
  display:none;
}
/* When moving the mouse over the submit button, add a darker green color */
input[type=submit]:hover {
  background-color: #ffaa00;
}
label {
  color:white;
}
/* Add a background color and some padding around the form */
.container-form {
  width:60vw;
  display:flex;
  justify-content: center;
  align-items: center;
}
input {
  transition: outline-color .7s linear;
}
input:focus, textarea:focus, select:focus{
  outline-color: #E3A324;
}
.error-message  {
  font-size: .5rem;
  line-height:20px;
  padding-left:1vw;
  margin-top:-1vh;
  color:#E3A324;
  font-weight: 400;
  letter-spacing: 1px;
}
<body>
   <h2>Napisz do nas:</h2>
   <p><span >*</span>pola oznaczone gwiazdką są wymagane aby wysłać wiadomość</p>
   <div >
      <form  id ="form-contact" action="action_page.php">
         <label for="fname">Imię i Nazwisko <span >*</span></label>
         <input type="text" id="name" name="name" placeholder="Podaj imię i nazwisko..." required>
         <label for="mailadress">Adres mailowy<span >*</span></label>
         <input type="mail" id="mailadress" name="mail" placeholder="podaj swojego maila..." required>
         <label for="mailadress">Telefon</label>
         <input type="text" id="phone-number" name="phone" placeholder="podaj nr telefonu...">
         <label for="title">Tytuł wiadomości<span >*</span></label>
         <input type="text" id="title" name="message-title" placeholder="podaj tytuł..." required>
         <label for="subject">Treść wiadomości:<span >*</span></label>
         <textarea id="message" name="mess-content" placeholder="napisz..." style="height:300px" required></textarea>
         <br>
         <div ></div>
         <input type="submit" id="send" value="Wyślij">
         <label >
            <input type="file">
            <p>Dodaj plik</p>
         </label>
      </form>
   </div>
</body>

CodePudding user response:

what is the point with regexTitltePattern?? and in testMessage you compare the length with undefined lng you didn't pass any value to it.

  •  Tags:  
  • Related