简体   繁体   中英

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>

id=author on your first input element.

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

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

The Markup Validator would have picked this up for you.

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

message has an extra "s".

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

You need to change "message" to "author"

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. ;)

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