Beast_Code
Beast_Code

Reputation: 3247

What is prevent my validation function not to run when the form is empty?

What exactly is happening to the form that is not passing the function? I am attempting to validate that the form is not empty by using this function:

JS:

function validateForm() {
    console.log("Validate");
    var y = document.forms["form"]["itemEntered"].value;
    if (y == null || y == "") {
        alert("Must enter an item");
        return false;
    }
}

HTML:

<div>
      <div id="center-container">
        <h4>Enter an Item for Your Shopping List:</h4>
        <hr />
        <form name="form" onsubmit="return validateForm()" method="post" >
          <label for="item">Item:</label> 
          <input required type="text" placeholder="Shopping Items" id="item" name="itemEntered" autocomplete="off" />
          <input type="button"  value="Enter" id="Enter" onclick="javascript:addItem();" />
        </form>
      </div>
    </div>

Project running in Code Pen http://cdpn.io/JGCDB

You can see that even if the field is empty it still display on the list.

I also tried using the required attribute in the form tag, but didn't work.

Upvotes: 2

Views: 548

Answers (2)

Xtian Macedo
Xtian Macedo

Reputation: 835

I found a few issues with your code, first of all onclick will execute before the validation, secondly you have declared your input as "button" rather than "submit", hence the click will not trigger the form submit event. Below is the corrected code, hope it helps.

<script type='text/javascript'>
function validateForm() {
    console.log("Validate");
    var y = document.forms["form"]["itemEntered"].value;
    if (y == null || y == "") {
        alert("Must enter an item");
        return false;
    }

    alert('passed validation...');
    addItem();
    return true;
}

function addItem() {
   alert('adding item...');
}
</script>

And here's the markup.

<div>
      <div id="center-container">
        <h4>Enter an Item for Your Shopping List:</h4>
        <hr />
        <form name="form" onsubmit="return validateForm()" method="post" >
          <label for="item">Item:</label> 
          <input required type="text" placeholder="Shopping Items" id="item" name="itemEntered" autocomplete="off" />
          <input type="submit" value="Enter" id="Enter" />
        </form>
      </div>
    </div>
</body>

Upvotes: 1

user3281996
user3281996

Reputation: 9

You need to add return true if the validation is correct

function validateForm() {
    console.log("Validate");
    var y = document.forms["form"]["itemEntered"].value;
    if (y == "") {
        alert("Must enter an item");
        return false;
    }
    return true;
}

Upvotes: 0

Related Questions