简体   繁体   中英

How to stop form submit if validation fails in javascript

Needing some help... I've researched solutions on stakeoverflow, but for some reason, my HTML form with validation, still submits, when it should not.

  <form class="submitForm" action="https://www.google.com" method="POST" id="form" target="_blank" onsubmit="return validateForm()">
      <span id="validationMessage" aria-live="polite"></span>
      <input class="nameInput" type="text" name="name" value="" id="name" placeholder="Name">
      <input class="urlInput" type="url" name="url" value="" id="url" placeholder="https://example.com">
      <button type="submit">go!</button>
  </form>

I've purposely removed required from the input fields, as I want to write my own validation.

But basically, the form should not submit, if the text input and url input fields have empty values.

But the form still submits! What have I done wrong?

Here's my function to check if the URL is valid. Or if it's value is empty:

  function validateForm(data) {
    console.log('validate form');

    var url = data.url;
    var pattern = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;

    if (pattern.test(url)) {
        console.log("Url is valid");
        validationMessage.innerHTML = '';
        return true;
    } else if (url.length === 0 || url === '') {
        console.log("Url is not valid!");
        validationMessage.innerHTML = 'URL format is not correct. Please check your url';
        return false;
    }
  }

And here's my function, to check if the text value field is empty:

  function validateName(data) {
    // console.log('validate form');
    console.log('data.name', data.name.length);

    if (data.name.length > 1) {
      // validationMessage.innerHTML = 'Please input a bookmark name';
      console.log('there is a name!');
      return true;
    } else if (data.name === "" || data.name.length === 0) {
      // validationMessage.innerHTML = 'Please input a bookmark name';
      console.log('no name!');
      return false;
    }
  }

They both console log the correct scenarios, but the form still submits...

Updated: To answer posters question, ValidateName() gets called here:

  // ADD A NEW BOOKMARK
  form.addEventListener('submit', function(e){
    e.preventDefault();

    let data = {
      name: nameInput.value,
      url: urlInput.value
    };

    validateName(data);
    // validateForm(data);


    $.ajax({
      url: urlInput.value,
      dataType: 'jsonp',
      statusCode: {
        200: function() {
          console.log( "status code 200 returned" );
          bookMarksArray.push(data);
          console.log("Added bookmark #" + data);
          localStorage.setItem("bookMarksArray", JSON.stringify(bookMarksArray));
          turnLoadingStateOn(bookMarksArray);
        },
        404: function() {
          console.log( "status code 404 returned. cannot add bookmark" );
        }
      }
   });
  });

Actually you need to return false from your submit handler if you don't want the form to submit

var namevalid = validateName(data);
!namevalid ? return false : null;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM