0

I have problems with my form submittiting even if the fields are not valid.

I've tried a lot of different code, but I'm currently with this.

const form  = document.getElementById('kontaktskjema');
    const email = document.getElementById('mail');
    const emailError = document.querySelector('#mail + span.errorkontakt');
    const navn = document.getElementById('navn');
    const navnError = document.querySelector('#navn + span.errorkontakt');
    const telefon = document.getElementById('telefon');
    const telefonError = document.querySelector('#telefon + span.errorkontakt')
    const message = document.getElementById('message');
    const messageError = document.querySelector('#message + span.errorkontakt')
    const navnboks = document.querySelector('.navnboks')
    const teleboks = document.querySelector('.teleboks')
    const mailboks = document.querySelector('.mailboks')
    const messageboks = document.querySelector('.messageboks')
    const vernboks = document.querySelector('.vernboks')
    const personvern = document.getElementById('checkbox');
    const personvernError = document.querySelector('#checkbox + span.errorkontakt')
    const submitbtn = document.getElementById('submitbtn');







    
    
    // THIS DIV WILL CONTAIN ERROR MESSAGES
    const errOutput = document.querySelector('.errorsOutput')


    email.addEventListener('input', function (event) {
      if (email.validity.valid) {
        mailboks.setAttribute("class", "data-validation-error-ok" )

        emailError.innerHTML = ''; 
        emailError.className = 'errorkontakt'; 
      } else {
        showError();
      }
    
    });


    navn.addEventListener('input', function (event) {

        if (navn.validity.valid) {
          navnError.innerHTML = '';
          navnError.className = 'errorkontakt';
          navnboks.setAttribute("class", "data-validation-error-ok" )

        } else {
            showError();
        }

    })

     telefon.addEventListener('input', function (event) {

        if (telefon.validity.valid) {
            telefonError.innerHTML = '';
            telefonError.className = 'errorkontakt';
            teleboks.setAttribute("class", "data-validation-error-ok" )

        } else {
            showError();
        }

    })

    
    message.addEventListener('input', function (event) {

        if (message.validity.valid) {
          messageboks.setAttribute("class", "data-validation-error-ok" )

            messageError.innerHTML = '';
            messageError.className = 'errorkontakt';

        } else {
            showError();
        }

    })

    personvern.addEventListener('change', function (event) {

      if (personvern.checked == true) {
        vernboks.setAttribute("class", "data-validation-error-ok" )

      } else {
          showError();
      }

  })




function makeRed() {
  if (!navn.validity.valid) {
    navnboks.setAttribute("class", "data-validation-error-true")
  }

  if (!email.validity.valid) {
    mailboks.setAttribute("class", "data-validation-error-true")
  }
  if (!telefon.validity.valid) {
    teleboks.setAttribute("class", "data-validation-error-true")
  }
  if (!message.validity.valid) {
    messageboks.setAttribute("class", "data-validation-error-true")
  }
  if (!personvern.checked == true) {
    vernboks.setAttribute("class", "data-validation-error-true")
  }

};

function divFill() {
  if (navnError.textContent != '') {
    errOutput.innerHTML += '<li>Navn</li>'
  }
  if (emailError.textContent != '') {
    errOutput.innerHTML += '<li>E-mail</li>'
  }
  if (telefonError.textContent != '') {
    errOutput.innerHTML += '<li>Telefonnummer</li>'
  }
  if (messageError.textContent != '') {
    errOutput.innerHTML += '<li>Beskjed</li>'
  }

}

    function showError() {
    
      errOutput.innerHTML = ''
  

      if(navn.validity.valueMissing) {
        navnError.textContent = '* Du må fylle inn navnet ditt';
        navnError.setAttribute("class", "data-validation-error-true" )
    } else if(navn.validity.tooShort) {
    navnError.textContent = '* Du må fylle inn hele navnet ditt'
    }
    

      
      if(email.validity.valueMissing) {
        emailError.setAttribute("class", "data-validation-error-true" )
        emailError.textContent = '* Vennligst fyll inn e-posten din';
      } else if(email.validity.typeMismatch) {
 
        emailError.textContent = '* Dette er ikke en gyldig e-postadresse.';
      } else if(email.validity.tooShort) {

        emailError.textContent = `* Email should be at least ${ email.minLength } characters; you entered ${ email.value.length }.`;
      }


      
      if(telefon.validity.valueMissing) {
          telefonError.textContent = '* Du må fylle inn telefonnummeret ditt'
          telefonError.setAttribute("class", "data-validation-error-true" )

      } else if(telefon.validity.tooShort) {
          telefonError.textContent = '* Du mangler ett eller flere tall. Vennligst dobbeltsjekk.'
      }

      
      if(message.validity.valueMissing) {
        messageError.setAttribute("class", "data-validation-error-true" )
        messageError.textContent = '* Beskjeden mangler, vennligst fyll inn'
      } else if(message.validity.tooShort) {
        messageError.textContent = `* Beskjed må være minst ${ message.minLength } tegn.`;
      }

   }
  
      

      emailError.className = 'errorkontakt kontaktactive';
      navnError.className = 'errorkontakt kontaktactive';
      telefonError.className = 'errorkontakt kontaktactive';
      messageError.className ='errorkontakt kontaktactive';

console.log(form)

form.addEventListener('submit', function(event) {
  if (!navn.validity.valid || !email.validity.valid || !telefon.validity.valid || !message.validity.valid) {
      makeRed();
      divFill();
      event.preventDefault();
      console.log('Runs')

  }})
 <div id="contact-form-wrapper" class="align-right-50 lazyload">
          <div id="contact-form-padding">
            <h2>Send oss en melding</h2>
            <p><span class="required">*</span> obligatorisk felt som du må fylle ut</p><br>
            
            <div class="errorsOutput">
            </div>
            <div class="skjema">
            <form id="kontaktskjema" action="nyhandler.kontakt.php" method="post"  novalidate>

              <input type="hidden" id="sendtfra" name="Sidetittel" value="{title}" />
              <input type="hidden" id="sendtfraURL" name="Side URL" value="{url}" />
              
              <div class="navnboks">  
                    <p>
                    <label for="navn">
                    <span>* Navn:</span>
                  <input type="text" id="navn" name="navn" required minlength="3" class="input-text w100">
                  <span class="errorkontakt" aria-live="polite"></span>
                </label>
              </p>    
            </div>
              
            <div class="mailboks">
                  <p>
                    <label for="mail">
                      <span>* E-post:</span>
                      <input type="email" id="mail" name="mail" required minlength="6" class="input-text w100">
                      <span class="errorkontakt" aria-live="polite"></span>
                    </label>
                  </p>
                </div>
              
                <div class="teleboks"> 
                      <p>
                        <label for="telefon">
                          <span>* Telefonnummer:</span>
                          <input type="tel" id="telefon" name="telefon" required minlength="8"  class="input-text w100">
                          <span class="errorkontakt" aria-live="polite"></span>
                        </label>
                      </p>
                    </div>
              
                    <div class="messageboks"> 
                          <p>
                            <label for="message">
                              <span>* Melding:</span>
                              <input type="text" id="message" name="message" required minlength="10" class="input-text w100">
                              <span class="errorkontakt" aria-live="polite"></span>
                            </label>
                          </p>
                        </div>
                        <div class="vernboks">
                            <input type="hidden" id="recapta" name="g-recaptcha-response" />
                            <p>
                              <label for="personvern">
                                <div class="personvern">
                                <span>* Personvern:</span>
                                <br>
                                <input type="checkbox" id="checkbox" name="checkbox" required>
                                <span>Jeg har lest og godkjent <a href="/ac/personvern">Personvernserklæringen (åpnes i nytt vindu)</a></span>
                                <span class="errorkontakt" aria-live="polite"></span>
                              </div>
                              </label>
                            </p>
                          </div>
              <button type="submit" value="Send" class="button-send">Send</button>
            </form>
          </div>
          </div>
        </div>
        <div class="clear"></div>
    </div>

I know it's weirdly specific, and i'll probably clean it up after i get it to work. Right now the validation completes, and runs the functions makeRed() and divFill(), both functions are there to help with accessability issues when not valid, but the form still submits and goes to the handler php.

Thanks.

DOFFIZ
  • 13
  • 4
  • 1
    Does this answer your question? [Intercept a form submit in JavaScript and prevent normal submission](https://stackoverflow.com/questions/5384712/intercept-a-form-submit-in-javascript-and-prevent-normal-submission) – ikos23 Jun 02 '22 at 11:48
  • I suppose this has something to do with the invalid syntax, nested [form elements](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form) are not allowed. – Teemu Jun 02 '22 at 11:50
  • @Teemu Fixed it. Removed every additional
    element. Still sending the mail from the form. Thanks for answering though. I think it may be because the scripts loads after the form or something?
    – DOFFIZ Jun 02 '22 at 12:42
  • Put a `console.log('Runs')` in the function to see if it's run. Notice, that returning from an event listner doesn't do anything, you've to prevent the default action only when the form doesn't validate. – Teemu Jun 02 '22 at 12:47
  • @Teemu Yes, it runs. I moved the event.preventDefault into my if statement and removed the return false. Still submiting and sending the form, sadly. – DOFFIZ Jun 02 '22 at 12:57
  • Then the only imaginable reason is that you're calling `form.submit()` somewhere in your code, maybe in `makeRed` or `divFill` function. Calling the submit method of a form in JS doesn't trigger submit event, hence it can't be prevented. – Teemu Jun 03 '22 at 04:15
  • @Teemu I have edited my original post with the complete javascript file, including the functions. Can't find any place where it submits the form. – DOFFIZ Jun 03 '22 at 17:41
  • Does preveventDefault work if you remove the condition around it? – Slava Knyazev Jun 03 '22 at 17:43
  • @SlavaKnyazev Thank you for answering, but sadly no. Still submits. – DOFFIZ Jun 04 '22 at 13:28
  • I can't [reproduce the issue](https://jsfiddle.net/tkzxmvj1/) with your code, the form is submitted with the given code only when the entered data is correct, if the validation fails, the form is not submitted. – Teemu Jun 06 '22 at 04:24
  • You're correct! Recaptcha is submiting. var rcf = document.getElementsByName('g-recaptcha-response'); for(var i=0; i – DOFFIZ Jun 07 '22 at 07:56

1 Answers1

0

getElementsByTagName

will return the form tag's value in [0]th location.

So you might need to change your first line of your javascript code as :

const form = document.getElementsByTagName('form')[0];

It will work .

farooq
  • 1,603
  • 2
  • 17
  • 33
  • Hi and thanks for the answer. I would normally agree with you, but that was my initial code, I just changed it to [1] after realizing that [0] was my searchbar after console.logging a bit. – DOFFIZ Jun 02 '22 at 12:06
  • @DOFFIZ You can set id to form element and the access it by using document.getElementById . Why you are not using it ? – farooq Jun 02 '22 at 12:20
  • 1
    great question! I have fixed that now. Still sending the form though. Thinking it maybe got something to do with it loading after the form or something? No idea right about now, should probably go get some air before i continue. – DOFFIZ Jun 02 '22 at 12:40
  • How did you fix it though ? – farooq Jun 02 '22 at 12:41
  • Oh sorry, didn't fix the issue, just fixed the getElementById slipup. Still not working. const form = document.getElementById('kontaktskjema'); instead of const form = document.getElementsByTagName('form')[1]; – DOFFIZ Jun 02 '22 at 12:43
  • I have tried the same by copying your code into my local machine. it works perfectly. I'm not sure about your entire code. – farooq Jun 03 '22 at 05:20
  • I have edited my original post with the complete javascript file, including the functions now. – DOFFIZ Jun 03 '22 at 17:40