Adam Halasz
Adam Halasz

Reputation: 58301

Why my form doesn't validate correctly?

I'm trying to validate a form, but doesn't work :\ , When I submit the form goes to mail.php even if the required fields are missing, but I set onsubmit to validate() so it should check, but doesn't work. What's the problem with my code? I can't find it.

HTML:

<form action="mail.php" onsubmit="return validate()" method="post" class="contact-form" id="contactForm">

    <div id="errors"></div>

    <label for="author">Name:</label><br/><br/>

    <input type="text" name="author" id="message" /><br/><br/>

    <label for="author">Message:</label><br/><br/>

    <textarea name="message" id="message"></textarea><br/><br/>

    <input type="submit" class="button" value="Send Message"/>

</form>

Javascript:

    <script type="text/javascript">
    function error(message){
        return "<p class=\"error\">"+message+"</p>";
    }

    function validate(){
        var form     = document.getElementById("contactForm");
        var author     = document.getElementById("author");
        var message = document.getElementById("messsage");
        var errors    = document.getElementById("errors");
        alert(author.value);
        if(message.value == '' || author.value == ''){
            errors.innerHTML = error("Please fill in all fields.");
            return false;
        } else {
            return true;
        }

    }
</script>

Upvotes: 0

Views: 452

Answers (4)

Spudley
Spudley

Reputation: 168685

This is wrong:

<input type="text" name="author" id="message" />

Need to set name and id to the same values (you're using id="message" for the next field, so there's a clash.

Also both your label tags have for="author"; the second one is wrong.

I guess your problem here is too much copy+paste. ;)

Upvotes: 1

mcrumley
mcrumley

Reputation: 5700

var message = document.getElementById("messsage");

message has an extra "s".

<input type="text" name="author" id="message" />

You need to change "message" to "author"

Upvotes: 2

Quentin
Quentin

Reputation: 943569

You have two elements with the id message and none with author.

The Markup Validator would have picked this up for you.

Upvotes: 3

NimChimpsky
NimChimpsky

Reputation: 47290

id=author on your first input element.

Also check out jQuery it will save you time in the long run

Upvotes: 3

Related Questions