如何在用户退出页面之前验证表单

时间:2012-10-02 08:38:30

标签: javascript forms submit verify

  

可能重复:
  Best way to detect when user leaves a web page

我正在寻找一种功能,确保在用户离开页面之前已经验证了表单。

实际上我添加了许多必填字段所需的内容,但没有任何内容可以确保表单将被验证。

在用户退出网页之前,是否有某种方式可以验证表单是否已提交?

实际上我使用onclick='return confirm ("Do you really want to go out of the page ?")'

但是没有任何内容可以验证表单是否已提交。

尽全力接受我的决定。

亲切的问候。

SP。

2 个答案:

答案 0 :(得分:3)

为什么不在提交表单时返回值或设置隐藏字段,然后在用户离开时用JS检查此值?这不会阻止用户关闭原因窗口,但这是一个开始。

答案 1 :(得分:0)

There is onsubmit event on the form that accepts either true or false 

You can attach it to a function that return either true or flase

Example :


html form

  <form name="myForm" action="test.html" onsubmit="return validateForm()" method="post">
        name:


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



        <input type="submit" value="Submit" />
    </form>


Java Script Code


    <script type="text/javascript">

        function validateForm() {
            var x = document.forms["myForm"]["fname"].value;
            if (x == null || x == "") {
                alert("First name must be filled out");
                return false;
            }
            else {

                return true;
            }
        }
    </script>


if you leave the name empty : it will alert you

if not it will go to test.html

Hope this is helpful.