【代码笔记】Web-JavaScript-JavaScript表单验证

一,效果图。

 

二,代码。

复制代码
<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>JavaScript 表单验证</title>
    <script>
    function validateForm() {
        var x = document.forms["myForm"]["fname"].value;
        if (x == null || x == "") {
            alert("姓必须填写");
            return false;
        }
    }
    </script>
    <script>
    function validateForm() {
        var x = document.forms["myForm"]["email"].value;
        var atpos = x.indexOf("@");
        var dotpos = x.lastIndexOf(".");
        if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= x.length) {
            alert("Not a valid e-mail address");
            return false;
        }
    }
    </script>
</head>

<body>
    <form name="myForm" action="demo-form.php" onsubmit="return validateForm()" method="post">
        姓:
        <input type="text" name="fname">
        <input type="submit" value="提交">
    </form>
    <form name="myForm" action="demo-form.php" onsubmit="return validateForm();" method="post">
        Email:
        <input type="text" name="email">
        <input type="submit" value="Submit">
    </form>
</body>

</html>
复制代码

 

参考资料:《菜鸟教程》

 

posted @ 2019-01-07 09:22  花儿迎风笑  阅读(295)  评论(0编辑  收藏  举报