A C
A C

Reputation: 427

JavaScript Input Field Validation

I wrote validation code for a form, which goes:

function checkWholeForm(theForm) {
  // Create validation variables
  var valid = true;
  var validationMessage = "Please correct the following errors: \r\n";

  // Validate name
  if (document.getElementById('name').value.length == 0)
        {
            validationMessage = validationMessage + '  - Name is missing\r\n';
            valid = false;
        }

//(and there's a few other functions)

// Display alert box with errors if any errors found
  if (valid == false)
        {
            alert(validationMessage);
        }

        return valid;

  }

and then in the HTML page, it goes:

<form action="submit.php" method="post" enctype="text/plain" onsubmit="return checkWholeForm(this)">

and in the table is:

<input type="text" id="name" name="name" size="20" value="" />

But when I hit submit, an empty text box doesn't trigger the alert. What am I doing wrong?

Edit: http://jsbin.com/uvepin/2/edit for the full HTML and JS.

Upvotes: 0

Views: 201

Answers (2)

nnnnnn
nnnnnn

Reputation: 150030

If you open your browser's console (F12 in Chrome and IE; ctrl-shift-K in FF) you'll see that your code gives this error:

Uncaught ReferenceError: validationMessage is not defined 

...because you declared the variable as validMess. Then in your update to the question you renamed it to validMessage. But still your other code is referring to validationMessage.

// WRONG:
var validMessage = "Please correct the following errors: \r\n";

// RIGHT:
var validationMessage = "Please correct the following errors: \r\n";

Demo: http://jsfiddle.net/JH8hg/

UPDATE to go with your latest update:

In your jsbin.com demo, you have attempted to add an onsubmit handler to a button:

<input class="button" name="send" type="submit" value="Send!" onsubmit="return checkWholeForm(this)" />

...but buttons don't have an onsubmit event so this should be added to the form element:

<form action="mailto:[email protected]" method="post" enctype="text/plain"
      onsubmit="return checkWholeForm(this)">  

And that form element doesn't have a closing </form> tag.

And you forgot to give an id="email" to your email field which means you got a JS error when you tried to use document.getElementById('email').value.length.

Working demo with those things fixed: http://jsbin.com/ukepuh/1/edit

Upvotes: 0

box86rowh
box86rowh

Reputation: 3415

OK, many issues, you are using getElementById, but your id is not set for the email box, also to do form validation, change from type = submit to type = button and use onclick instead of onsubmit

my edited version: http://jsbin.com/ujeval/1/

Upvotes: 1

Related Questions