0

I have been searching across google and stack overflow and I cannot find an answer. So i'm hoping to get some help here.

I have this form and I need to make sure everything is valid in it before submitting. What they want is to display a message ONLY ONCE everything is valid then you can submit it, so the button is null until then more or less.

I have not done something like this before so this is somewhat new to me, I tried using a conditional statement with a bunch of and/or conditions. That does not seem to be working, I really do not know what else to try, because I'm used to the form validating once the submit button has been hit.

Thanks for any help!

This is where im at so far:

const firstName = document.querySelector("#first_name");
const lastName = document.querySelector("#last_name");
const phoneNumber = document.querySelector("#phone");
const emailInput = document.querySelector("#email");
const howDidYouHearLabel = document.querySelector("#how_did_you_hear_label");
const howDidYouHearMenu = document.querySelector("#how_did_you_hear_menu");
const pleaseSpecify = document.querySelector("#please_specify");
const pleaseSpecifyLabel = document.querySelector("#please_specify_label");
const promoInput = document.querySelector("#promo_code");
const termsAndConditionsLink = document.querySelector("#terms_and_conditions_link");
const zeroDisplay = document.querySelector("#zero");
const popUpBox =  document.querySelector("#popUpBox");
const hidePopUp = document.querySelector("#hide");
const validationMessage = document.querySelector("#validation_message");


function validateForm(firstName, lastName, phone, email, promo) {
  if( firstName.value && lastName.value != null
      && phone.value === phone.value.replace(/[^\d]/,'') 
      && email.value === /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/.test(email.value) 
      && promo.value === /^[a-z0-9]+$/i.test(promo.value)) {
    
      validationMessage.style.color = 'blue';
  }
};

document.addEventListener("keyup", validateForm(firstName, lastName, phoneNumber, emailInput, promoInput));

// Makes sure a valid email address was entered 
emailInput.addEventListener("input", (e) => {
  const emailInputValue = e.currentTarget.value;
  if( /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/.test(emailInputValue) != true) {
      emailInput.style.border = "thin solid red";
  } else {
      emailInput.style.border = "";
  }
});

// Makes sure a valid promo code was entered
promoInput.addEventListener("input", (e) => {
    const promoInputValue = e.currentTarget.value;
    if( /^[a-z0-9]+$/i.test(promoInputValue) != true) {
        promoInput.style.border = "thin solid red";
    } else {
        promoInput.style.border = "";
    }
  });

// Checks to see if a promo code has been entered or not, adds or removes required class as needed
promoInput.addEventListener('input', (e) => {
  if (promoInput.value === '') {
    howDidYouHearMenu.required = true;
    howDidYouHearLabel.classList.add("required")
  } else {
    howDidYouHearMenu.required = false;
    howDidYouHearLabel.classList.remove("required")
  }
});

// If the "Other" option is selected in the select menu, then "Please specify" becomes required, else it is not required
howDidYouHearMenu.addEventListener('change', (e) => {
  if(howDidYouHearMenu.value === "Other") {
    pleaseSpecifyLabel.style.display = 'block';
    pleaseSpecify.style.display = 'block';
    pleaseSpecify.required = true;
    pleaseSpecifyLabel.classList.add("required");
  } else {
      pleaseSpecifyLabel.style.display = 'none';
      pleaseSpecifyLabel.classList.remove("required");
      pleaseSpecify.style.display = 'none';
      pleaseSpecify.required = false;
  }
})
<h6 id="validation_message">You did it!</h6>
    <form id="contact_form" name="contact_form" method="POST">
      <fieldset>
        <legend>Contact Details</legend>

        <label for="first_name" class="required">First name:</label>
        <input type="text" required id="first_name" name="first_name" placeholder="First name" maxlength="30">

        <label for="last_name" class="required">Last name:</label>
        <input type="text" required id="last_name" name="last_name" placeholder="Last name" maxlength="30">

        <label for="phone" class="required">Phone:</label>
        <input type="tel" required onkeyup="this.value=this.value.replace(/[^\d]/,'')" id="phone" name="phone" placeholder="Phone number" maxlength="30">

        <label for="email" class="required">Email:</label>
        <div id="email_div">
          <input type="email" required name="email" id="email" placeholder="Email" maxlength="50">
          <label for="email" id="email_text">This field is required in order to receive an email confirmation.</label>
        </div>

        <label for="promo_code" id="promo_code_label">Promo Code:</label>
        <input type="text" name="promo_code" id="promo_code" placeholder="Promo code" maxlength="7">

        <label for="how_did_you_hear_menu" class="required" id="how_did_you_hear_label">How did you hear:</label>
        <select required name="how_did_you_hear_menu" id="how_did_you_hear_menu">
          <option value="Social Media">Social Media</option>
          <option value="From a friend">From a friend</option>
          <option value="Email">Email</option>
          <option value="Other">Other</option>
        </select>

        <label for="please_specify" id="please_specify_label">Please specify:</label>
        <textarea hidden name="please_specify" id="please_specify" rows="4" placeholder="Please specify" maxlength="255"></textarea>

        <div id="terms_and_conditons_div">
          <div id="zero" style="display:none"></div>
          <div id="text">
            <input type="checkbox" required name="terms_and_conditions" id="terms_and_conditions">
            <a href=# target="_self" id="terms_and_conditions_link" class=" required" required>I agree to the terms and conditions of this event.</a>
            <div id="popUpBox" style="display:none">
              <a id="hide" href=# target="_self" class="right">x</a>
              <p> All cancellation requests must be received by March 1, 2022 </p>
              <p> All cancellation requests are subject to a $100 cancellation fee.</p>
              <p>No one under the age of 16 will be allowed on the show floor. </p>
            </div>
         </div>

      </fieldset>
      <input type="submit" id="form_submit_btn" value="Submit">
    </form>
Stacks Queue
  • 848
  • 7
  • 18
Jay
  • 35
  • 4
  • What specifically does not seem to be working? – showdev Jun 28 '21 at 04:56
  • The validation message should change to blue, if everything is valid. it is not changing at all – Jay Jun 28 '21 at 04:58
  • 1
    @Jay I assume you've done some debugging. Any clues so far? It's a lot of code to try and 'spot the bug'. Perhaps you can cut it by like 80% to get a more minimal example that people can easily reproduce. You should try this yourself too. – Evert Jun 28 '21 at 05:13
  • Your `keyup` handler might be firing `validateForm()` only once upon assignment, [like in this answer](https://stackoverflow.com/a/14425411/924299). Also, [`test()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test) returns `true` or `false`, so `email.value === /^$/.test(email.value)` seems inappropriate. It might help to build a [working example](https://stackoverflow.com/help/minimal-reproducible-example) to help demonstrate and troubleshoot the issue. – showdev Jun 28 '21 at 05:18
  • Use HTML5 buit-in form validation: https://developer.mozilla.org/en-US/docs/Learn/Forms/Form_validation#using_built-in_form_validation – sssurii Jun 28 '21 at 05:50

2 Answers2

0

Change if( firstName.value && lastName.value != null To if( firstName.value != null && lastName.value != null

-1

If u find it difficult to validate inputs in your form then you must try this validator package from npm. If u have any difficulties in understanding that package feel free to comment your issue

  • I tried but it said file not found when I tried to import it into my HTML – Jay Jun 28 '21 at 05:38
  • Are you using React if not give it a try. But for this issue when I started web development person has suggesten=d me to read this article on form validation in HTML and javascript https://developer.mozilla.org/en-US/docs/Learn/Forms/Form_validation – K.V.Praneeth Reddy Jun 28 '21 at 05:53