JavaScript基础-form表单验证

本文介绍两种JavaScript表单验证方法:使用alert提示框和标签方式。前者适用于学习,后者提升用户体验,推荐使用。通过实例展示了如何在HTML中实现这两种验证。

表单验证的两种方式:

一、使用alert提示框

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <title>JavaScript基础</title>
    <script type="text/javascript">
        function check_form()
        {
            if(document.form1.title.value == "")
            {
                alert('标题不能为空!');
                document.form1.title.focus();
                return false;
            }

            if(document.form1.content.value == "")
            {
                alert('内容不能为空!');
                document.form1.content.focus();
                return false;
            }

            return true;
        }
    </script>
</head>

<body>
    <form method="post" action="" name="form1" onsubmit="return check_form()">
        标题:<input type="text" name="title"><br><br>
        内容:<textarea rows="10" cols="30" name="content"></textarea><br><br>
        <input type="submit" value="提 交">
    </form>
</body>
</html>

这种验证方式适合学习使用,但是真实项目中一般不建议用alert,用户体验不好。

二、标签方式

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <title>JavaScript基础</title>
    <script type="text/javascript">
        function check_form(tmp_form)
        {
            var err = document.getElementById('error_tips');

            if(tmp_form.title.value == "")
            {
                err.innerHTML = "标题不能为空!";
                err.style.color = "red";
                err.style.fontSize = "9px";
                tmp_form.title.focus();
                return false;
            }

            if(tmp_form.content.value == "")
            {
                err.innerHTML = "内容不能为空!";
                err.style.color = "red";
                err.style.fontSize = "9px";
                tmp_form.title.focus();
                return false;
            }
            return true;
        }
    </script>
</head>

<body>
<form method="post" action="" name="form1" onsubmit="return check_form(this);">
    <p><label for="title">标题:</label><input type="text" name="title" id="title"></p>
    <p><label for="content">内容:</label><textarea rows="10" cols="30" name="content" id="content"></textarea></p>
    <p><input type="submit" value="提 交"></p>
    <p id="error_tips">&nbsp;</p>
</form>
</body>
</html>

一般推荐使用标签方式,既可以醒目的提醒用户,又不会因为频繁跳出的提示框造成用户体验下降;另外,由于html标签不能使用name属性,只能使用id属性访问,所以通过document对象的getElementById方法,获取到保存至变量err中,方便使用。在tmp_form对象中是无法直接访问标签error_tips的。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

虾米大王

有你的支持,我会更有动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值