1

I am having difficulty validating a form in javascript. I'm currently checking just a text field and it doesn't work. My code is as followed:

index.html:

<html xmlns = "http://www.w3.org/1999/xhtml">
<head> 
    <title>
        Validation Form
    </title>
    <script type = "text/javascript" src ="vForm.js">
    </script>
</head>
<body>
    <form id = "myForm" action ="">
        First name: <input type="text" name="fname"></br>
        Last name: <input type="text" name="lname"></br>
        Password: <input type="password" name="pass1"></br>
        Re-enter password: <input type="password" name="pass2"></br>
        Email: <input type="text" name="email"></br>
        Phone: <input type="text" name="phone"></br>
        Address: <input type="text" name="add"></br>
        Date: <input type="date" name="date"></br>
        Time: <input type="time" name="time"></br>
        <input type="reset" name="reset">
        <input type="submit" name="submit">
    </form>
    <script type = "text/javascript" src ="vFormRun.js">
    </script>
</body>
</html>

vForm.js:

function validateForm()
{
    var fname = document.getElementById("fname");
    var lname = document.getElementById("lname");
    var pass1 = document.getElementById("pass1");
    var pass2 = document.getElementById("pass2");
    var email = document.getElementById("email");

    if(fname == "")
    {
        alert("Please enter first name")
        return false;
    }
    else
    {
        return true;
    }
}

vFormRun.js:

document.getElementById("myForm").onsubmit = validateForm;
RASG
  • 5,988
  • 4
  • 26
  • 47
Ryan Sayles
  • 3,389
  • 11
  • 56
  • 79
  • 4
    basic javascript. missed `.value`. – RASG Sep 30 '12 at 17:57
  • 1
    off-topic: you haven't specified if you're validating the data on the server side as well, but in case you aren't, be aware that JS validation can be bypassed by the user: it can be helpful, but it shouldn't be considered secure. Validate the same data on the server side as well. – Spudley Sep 30 '12 at 17:58
  • [The homework tag is now officially deprecated](http://meta.stackexchange.com/questions/147100/the-homework-tag-is-now-officially-deprecated?cb=1) – nKandel Sep 30 '12 at 17:58
  • Here is a great example of where debugging (via Firebug or the equivalent tool in Chrome etc) would be really useful. Put a breakpoint on the line after `var fname = ...` and you would see that the element has a *property* called value with the right thing in. Learn it, save yourself a lot of effort. – Phil H Sep 30 '12 at 17:59
  • @RASG is correct, should be: `var fname = document.getElementById("fname").value; var lname = document.getElementById("lname").value; var pass1 = document.getElementById("pass1").value; var pass2 = document.getElementById("pass2").value; var email = document.getElementById("email").value;` – pixel 67 Mar 16 '14 at 23:36

3 Answers3

3

You need to give .value to each of it. And also, give an id of the same name.

function validateForm()
{
 var fname = document.getElementById("fname");
 var lname = document.getElementById("lname");
 var pass1 = document.getElementById("pass1");
 var pass2 = document.getElementById("pass2");
 var email = document.getElementById("email");

 if(fname.value == "")
 {
   alert("Please enter first name")
   return false;
 }
 else
 {
   return true;
 }
}
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
2
document.getElementById("fname");

That will only work if you have an element with an ID of fname, which you do not.

You can set the ID attribute to an element like so:

<input type="text" name="fname" id="fname">

Alternatively, you can reference the form elements like this:

var fname = document.forms["myForm"]["fname"]

Then you want to get it's value property when comparing.

fname.value

The <br> tag is self closing, so it should be <br /> instead of </br>

sachleen
  • 30,730
  • 8
  • 78
  • 73
  • 1
    Still, don't let people downvote you! :P Check your answer, it is not correct. I don't understand which illiterate upvoted you. ;) You did the same mistake as the OP did... :) – Praveen Kumar Purushothaman Sep 30 '12 at 17:59
  • There's no need for name calling here. – sachleen Sep 30 '12 at 18:03
  • 1
    @PraveenKumar But they did point out something important - that the elements need an `id` attribute for it to work at all! Still, the function needs to use `.value` as everyone's pointed out. – Ian Sep 30 '12 at 18:53
-1

Here is the solution...

function validateForm(form) {
    var fname = form.fname,
        lname = form.lname,
        pass1 = form.pass1,
        pass2 = form.pass2,
        email = form.email;

    if(fname && fname.value === "") {
        alert("Please enter first name");
        document.getElementById('result').innerHTML = 'Invalid';
        return false;
    }
    document.getElementById('result').innerHTML = 'Passed';
    return true;
}
<form id="myForm" action="" onsubmit="validateForm(this)">
    First name: <input type="text" name="fname"><br/>
    Last name: <input type="text" name="lname"><br/>
    Password: <input type="password" name="pass1"><br/>
    Re-enter password: <input type="password" name="pass2"><br/>
    Email: <input type="text" name="email"><br/>
    Phone: <input type="text" name="phone"><br/>
    Address: <input type="text" name="add"><br/>
    Date: <input type="date" name="date"><br/>
    Time: <input type="time" name="time"><br/>
    <input type="reset" name="reset">
    <input type="submit" name="submit">
  <p id="result">
  </p>
</form>

There were a few issues here that I corrected.

  1. I changed all of the var declarations to use one var declaration. This is a best practice.
  2. In the if statement I added a check for the variable fname to make sure it exists and is not null (prevents a null reference error).
  3. In the if statement you need to check the value attribute of the filed, not the field itself. In your old code if it is blank or not the field should be there and would have always returned true.
  4. I changed the comparison to use === instead of ==. When using ==, if the value is "false" or 0 it will return true. See "Difference between == and === in JavaScript".
  5. You were missing a semicolon at the end of the alert statement.
  6. If the body of the if ends with a return then you do not need an else block. Cuts down the amount of code (downloads faster) and makes it easier to read.
Community
  • 1
  • 1
Eric
  • 6,563
  • 5
  • 42
  • 66
  • What was the down vote for? If there is something wrong with the answer I would like to know (via a comment) so that everyone can benefit from better answers. – Eric Sep 30 '12 at 19:10
  • Probably because you missed the obvious one: no elements in the form have any IDs so you can't do `getElementById`. All of your other points are valid. – sachleen Sep 30 '12 at 21:40
  • @sachleen , can you verify that my changes to the example are now causing it work? – Eric Oct 29 '15 at 16:21