简体   繁体   中英

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.

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/

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:chandra.apoorv@gmail.com" 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

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