Home > Enterprise >  Contact form and boolean variables in Javascript
Contact form and boolean variables in Javascript

Time:05-19

I am working on a contact form and I want it to disappear after different validations. Everything works fine but I'm a bit of a perfectionist. I use a boolean variable ('IsValid') to delete the contact form and add a message.

The only thing I don't understand is the fact that if my textarea is filled, the other boxes don't need to be validated to delete the form.

Can you tell me what is wrong with my code?


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;
});

CodePudding user response:

Each of your validation checks call setSuccesFor() if that validation succeeds. This overrides all the previous validations.

You should initialize isValid to true. Failing validations can set it to false, but they shouldn't set it back to true. So remove isValue = true from setSuccesFor() -- they should just set the style of the input, not reset this variable.

CodePudding user response:

Your setSuccessFor function sets isValid to true.

messageValue is the last item validated, so if it passes, isValid will be true and your submit listener removes the form, regardless of the status of the other inputs.

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();
    // ...

I'd recommend you check out the Constraint Validation API.

  • Related