Javascript表单验证:表单在错误返回时提交:

时间:2012-08-01 07:30:48

标签: forms html5 javascript-events validation

当我尝试使用javascript验证表单时,它会提醒警报,但是表单会被提交,因为没有任何事情发生eventhoght false返回,警报仅在第一次按下提交按钮时工作。有人可以告诉我我做错了什么:

使用Javascript:

 function checkForm() {

       var name, email, text;

        name =  document.contact.userName.value;
        email = document.contact.email.value;
        text =  document.contact.textarea.value;

        //document.write(name + " " + email + " " + text);

        if (name == "" || email =="" || text=="")    {

             alert("Please fill all fields before submitting!");
             return false;

        }else if (!looksLikeMail(email))     {

         alert("Please enter you real email!");
             return false;
        }else       {

             alert("Your feedback was sent, Thank you!");
             return true;
            }    
 }

function looksLikeMail(str)     {

              var lastAtPos = str.lastIndexOf('@');
              var lastDotPos = str.lastIndexOf('.');
              return ((lastAtPos < lastDotPos) && lastAtPos > 0 && str.indexOf('@@') == -1 && lastDotPos > 2 && (str.length - lastDotPos) > 2);
>        }

HTML:

<form name="contact" action="login" method="POST" onsubmit="checkForm()">
                <input type="hidden" name="page" value="feedback">
                <div data-role="fieldcontain">
                    <fieldset data-role="controlgroup" data-mini="true">
                        <label for="textinput1">
                            Name:
                        </label>
                        <input id="name" placeholder="Enter your full name" value="" type="text" name="userName"/>
                    </fieldset>
                </div>
                <div data-role="fieldcontain">
                    <fieldset data-role="controlgroup" data-mini="true">
                        <label for="textinput2">
                            Email
                        </label>
                        <input id="email" placeholder="Enter your email" value="" type="email" name="email" />
                    </fieldset>
                </div>
                <div data-role="fieldcontain">
                    <fieldset data-role="controlgroup">
                        <label for="textarea1">
                            Feedback
                        </label>
                        <textarea id="textarea" placeholder="Enter your text here" name="textarea"></textarea>
                    </fieldset>
                </div>
                <input type="submit" data-inline="true" data-theme="b" data-icon="check" data-iconpos="right" value="Submit" />
            </form>

1 个答案:

答案 0 :(得分:3)

更改

<form name="contact" action="login" method="POST" onsubmit="checkForm()">

<form name="contact" action="login" method="POST" onsubmit="return checkForm()">

如果您的函数返回false,onsubmit将取消提交,但仅当onsubmit也将返回false时。所以你必须传递checkForm()的返回值。