Aamir
Aamir

Reputation: 2424

JavaScript and HTML form validation

I tried to do a simple validation on a button, but when I click the button without entering anything it still goes to testValidation1.html instead of popping up the alert window.

<html>

<head>
</head>

<body>

      <form action="testValidation1.html">

         Parameter1 : 
          <input type = 'text' name = 'param1'/><br>

          <input type='submit' value = 'submit' onclick = 'return validateForm()'>
      </form>

      <script type="text/javascript">

      function validateForm() {
             var f1 = document.forms[0];
             var p1 = f1.param1;

             if(p1.value.length == 0) {

                alert('Plz enter parameters');
                p1.focus();
                return false;
             }  
     }

      </script>


</body>
</html>

Upvotes: 0

Views: 64

Answers (1)

Sam Greenhalgh
Sam Greenhalgh

Reputation: 6136

you might find it easier to use the submit event of the form to validate

function validateForm(event) {
    var form = this;
    var p1 = form.elements['param1'];
    if(p1.value.length === 0) {
        alert('Plz enter parameters');
        p1.focus();
        event.preventDefault();
        return false;
    }
}

document.getElementById('form').addEventListener('submit', validateForm);

http://jsfiddle.net/7j0usuam/

Upvotes: 2

Related Questions