javascript - Javascript 中的联系表格和布尔变量

const form = document.getElementById('formContact');
const nameContact = document.getElementById('name');
const emailContact = document.getElementById('email');
const messageContact = document.getElementById('message');
const headerContact = document.querySelector('.headerContact')
const thankYou = document.querySelector('.Thankyou');

const isValidEmail = (email) => {
  const re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
  return re.test(String(email).toLowerCase());
};


let isValid = true;

function checkInputs(){

  //get the values from the inputs or textarea

  const nameValue = nameContact.value.trim();
  const emailValue = emailContact.value.trim();
  const messageValue = messageContact.value.trim();

  if (nameValue === ''){
    //show error
    //add error class
    setErrorFor(nameContact, 'Name cannot be blank');
  } else{
    //add success class
    setSuccesFor(nameContact);
  }

  if (emailValue === ''){
    //show error
    //add error class
    setErrorFor(emailContact, 'Email cannot be blank');
  } else if(!isValidEmail(emailValue)){
    setErrorFor(emailContact, 'Please add a valid email adress');
  } else{
    setSuccesFor(emailContact);
  }

  if (messageValue === ''){
    //show error
    //add error class
    setErrorFor(messageContact, 'Message cannot be blank');
  } else if (messageValue.length < 20){
    setErrorFor(messageContact, 'Message need to be at least 20 characters');
  }
  else{
    //add success class
    setSuccesFor(messageContact);
  }

}

function setErrorFor(input, message){
  isValid=false;
  const formControl = input.parentElement; 
  const errorContactMessage = formControl.querySelector('#Error');

  //add error message inside the span
  errorContactMessage.innerText = message;

  //add error class
  formControl.className = 'form-control error';

}

function setSuccesFor(input){
  isValid=true;
  const formControl = input.parentElement; 
  const errorContactMessage = formControl.querySelector('#Error');
  //remove message inside the span
  errorContactMessage.innerText='';

  //add success class
  formControl.className = 'form-control success';

}

form.addEventListener('submit', (e) =>{
  e.preventDefault();
  checkInputs();
  if(isValid){
    form.remove();
    headerContact.classList.add('hide');
    thankYou.classList.remove('hide');
    document.querySelector('#merci').innerHTML = `<h3>Dear ${nameThk}, thank you for reaching out ! </h3>`;
    
  }

});

let nameThk = "";
nameContact.addEventListener('input', (e) =>{
  nameThk = e.target.value;
});
.containerContact {
  background-color: #F8F8F8;
  width: 100%;
  max-width: 100%;
  padding: 0.5rem;
  display: block;
}

.containerContact h2 {
  margin-bottom: 0.5rem;
}

.form-control {
  margin-bottom: 0.25rem;
  position: relative;
}

.form-control input {
  display: block;
  width: 100%;
  height: 2rem;
  padding-left: 0.5rem;
  background: transparent;
  border: 0.025rem solid #000000;
  outline: none;
  font-size: 0.8125rem;
  color: #000000;
}

.form-control input::-webkit-input-placeholder {
  color: #000000;
}

.form-control input:-ms-input-placeholder {
  color: #000000;
}

.form-control input::-ms-input-placeholder {
  color: #000000;
}

.form-control input::placeholder {
  color: #000000;
}

.form-control textarea {
  width: 100%;
  height: 10rem;
  background: transparent;
  border: 0.025rem solid #000000;
  outline: none;
  font-family: Arial, Helvetica, sans-serif;
  padding: 0.5rem;
  font-size: 0.8125rem;
  color: #000000;
  resize: none;
}

.form-control textarea::-webkit-input-placeholder {
  color: #000000;
}

.form-control textarea:-ms-input-placeholder {
  color: #000000;
}

.form-control textarea::-ms-input-placeholder {
  color: #000000;
}

.form-control textarea::placeholder {
  color: #000000;
}

.form-control i {
  position: absolute;
  top: 0.5rem;
  right: 0.5rem;
  visibility: hidden;
}

.form-control #textareaChecks {
  position: absolute;
  top: 8.5rem;
  right: 0.5rem;
}

.form-control.success input {
  border-color: green;
}

.form-control.success i.fa-check-circle {
  visibility: visible;
  color: green;
}

.form-control.error input {
  border-color: red;
}

.form-control.error i.fa-exclamation-circle {
  visibility: visible;
  color: red;
}

.form-control.success textarea {
  border-color: green;
}

.form-control.success i.fa-check-circle {
  visibility: visible;
  color: green;
}

.form-control.error textarea {
  border-color: red;
}

.form-control.error i.fa-exclamation-circle {
  visibility: visible;
  color: red;
}

#Error {
  font-weight: 500;
  font-size: 0.75rem;
  font-style: italic;
  color: red;
  margin: 0;
  padding: 0;
}

#ContactSubmit {
  width: 100%;
  height: 2rem;
  background: #1e1e1e;
  outline: none;
  border: 0.025rem solid #000000;
  color: #FFFFFF;
}

.containerThank {
  height: 300px;
  display: -ms-grid;
  display: grid;
}

.containerThank h3 {
  margin: 0;
  text-align: center;
  -ms-flex-item-align: end;
      align-self: flex-end;
  font-size: 18px;
  font-weight: bold;
}

.containerThank p {
  -ms-flex-item-align: start;
      align-self: flex-start;
  text-align: center;
  font-size: 13px;
  padding-top: 0.5rem;
}

.hide {
  display: none;
}
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="css/index.css">
  <script src="https://kit.fontawesome.com/2dc9b6eb01.js" crossorigin="anonymous"></script>
  <title>Statsmap.ch</title>
</head>
<body>
  
  
    <section class="Contact">
        <div class="containerContact">
          <div class="headerContact">
            <h2>Contact</h2>
          </div>
          <form action=""  class="formContact" id="formContact" novalidate>
            <div class="form-control">
              <input type="text"  id="name" placeholder="First and Last name">
              <i class="fas fa-check-circle"></i>
              <i class="fas fa-exclamation-circle"></i>
              <span id="Error"></span>
            </div>

            <div class="form-control">
              <input type="email"  name = "email" id="email" placeholder="Please enter your email">
              <i class="fas fa-check-circle"></i>
              <i class="fas fa-exclamation-circle"></i>
              <span id="Error"></span>
            </div>

            <div class="form-control">
                <textarea id="message" type="text" placeholder="Message"></textarea>
                <i id="textareaChecks" class="fas fa-check-circle"></i>
                <i id="textareaChecks" class="fas fa-exclamation-circle"></i>
                <span id="Error"></span>                
              </div>
              <button id="ContactSubmit">Submit</button>
          </form>
          <div class="Thankyou hide">
            <div class="containerThank">
            <h3 id="merci"></h3>
            <p>Our team is going to get back to you as soon as possible</p>
            </div>
          </div>
        </div>
      </div>
    </section>
  </div>
 
  
  <script src="JS/contact.js"></script>
  <script src="JS/newsletter.js"></script>
  <script src="JS/script.js"></script>
  <script src="JS/scroll.js"></script>
</body>
</html>

我正在处理一个联系表格,我希望它在不同的验证后消失。一切正常,但我有点完美主义者。我使用布尔变量 ('IsValid') 来删除联系表单并添加消息。

我唯一不明白的是,如果我的 textarea 已填满,则无需验证其他框即可删除表单。

你能告诉我我的代码有什么问题吗?

const form = document.getElementById('formContact');
const nameContact = document.getElementById('name');
const emailContact = document.getElementById('email');
const messageContact = document.getElementById('message');
const headerContact = document.querySelector('.headerContact')
const thankYou = document.querySelector('.Thankyou');

const isValidEmail = (email) => {
  const re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
  return re.test(String(email).toLowerCase());
};


let isValid = false;

function checkInputs(){

  //get the values from the inputs or textarea

  const nameValue = nameContact.value.trim();
  const emailValue = emailContact.value.trim();
  const messageValue = messageContact.value.trim();

  if (nameValue === ''){
    //show error
    //add error class
    setErrorFor(nameContact, 'Name cannot be blank');
  } else{
    //add success class
    setSuccesFor(nameContact);
  }

  if (emailValue === ''){
    //show error
    //add error class
    setErrorFor(emailContact, 'Email cannot be blank');
  } else if(!isValidEmail(emailValue)){
    setErrorFor(emailContact, 'Please add a valid email adress');
  } else{
    setSuccesFor(emailContact);
  }

  if (messageValue === ''){
    //show error
    //add error class
    setErrorFor(messageContact, 'Message cannot be blank');
  } else if (messageValue.length < 20){
    setErrorFor(messageContact, 'Message need to be at least 20 characters');
  }
  else{
    //add success class
    setSuccesFor(messageContact);
  }

}

function setErrorFor(input, message){
  isValid=false;
  const formControl = input.parentElement; 
  const errorContactMessage = formControl.querySelector('#Error');

  //add error message inside the span
  errorContactMessage.innerText = message;

  //add error class
  formControl.className = 'form-control error';

}

function setSuccesFor(input){
  isValid=true;
  const formControl = input.parentElement; 
  const errorContactMessage = formControl.querySelector('#Error');
  //remove message inside the span
  errorContactMessage.innerText='';

  //add success class
  formControl.className = 'form-control success';

}

form.addEventListener('submit', (e) =>{
  e.preventDefault();
  checkInputs();
  if(isValid){
    form.remove();
    headerContact.classList.add('hide');
    thankYou.classList.remove('hide');
    document.querySelector('#merci').innerHTML = `<h3>Dear ${nameThk}, thank you for reaching out ! </h3>`;
    
  }

});

let nameThk = "";
nameContact.addEventListener('input', (e) =>{
  nameThk = e.target.value;
});

回答1

如果验证成功,您的每个验证检查都会调用 setSuccesFor()。这会覆盖所有先前的验证。

您应该将 isValid 初始化为 true。验证失败可以将其设置为 false,但不应将其设置回 true。所以从 setSuccesFor() 中删除 isValid = true -- 他们应该只设置输入的样式,而不是重置这个变量。

回答2

您的 setSuccessFor 函数将 isValid 设置为 true。

messageValue 是最后验证的项目,因此如果通过,isValid 将为真,并且您的提交侦听器将删除表单,而不管其他输入的状态如何。

let isValid = false;

function setSuccesFor(input){
  isValid=true; // <== sets the whole thing to valid
  // ...other stuff...
}

form.addEventListener('submit', (e) =>{
  e.preventDefault();
  checkInputs();
  if(isValid){ // <== a single input will set this to true
    form.remove();
    // ...

我建议您查看 https://developer.mozilla.org/en-US/docs/Learn/Forms/Form_validation#validating_forms_using_javascript

相似文章

最新文章