<!DOCTYPE html>
<html>
<head>
  <title>表单验证 - 姓名、邮箱和留言</title>
  <script>
    function validateForm() {
      var name = document.forms["myForm"]["name"].value;
      var email = document.forms["myForm"]["email"].value;
      var message = document.forms["myForm"]["message"].value;
<pre><code>  if (name == &quot;&quot;) {
    alert('姓名不能为空');
    return false;
  }

  if (email == &quot;&quot;) {
    alert('邮箱不能为空');
    return false;
  }

  if (message == &quot;&quot;) {
    alert('留言不能为空');
    return false;
  }
}
</code></pre>
  </script>
</head>
<body>
  <h2>留言板</h2>
  <form name="myForm" onsubmit="return validateForm()" method="post">
    <label for="name">姓名:</label>
    <input type="text" id="name" name="name"><br>
<pre><code>&lt;label for=&quot;email&quot;&gt;邮箱:&lt;/label&gt;
&lt;input type=&quot;email&quot; id=&quot;email&quot; name=&quot;email&quot;&gt;&lt;br&gt;

&lt;label for=&quot;message&quot;&gt;留言:&lt;/label&gt;
&lt;textarea id=&quot;message&quot; name=&quot;message&quot;&gt;&lt;/textarea&gt;&lt;br&gt;

&lt;input type=&quot;submit&quot; value=&quot;提交&quot;&gt;
</code></pre>
  </form>
  <p>本示例代码演示了如何使用 JavaScript 的 <code>validateForm</code> 函数验证表单。该函数检查姓名、邮箱和留言字段是否为空。如果为空,则使用 <code>alert</code> 函数显示相应的错误消息,并返回 <code>false</code> 以阻止表单提交。</p>
  <p>请注意,这只是一个简单的前端验证,仅验证是否为空。在实际开发中,可能需要更严格的验证,比如验证邮箱格式是否正确、留言的长度限制等。</p>
</body>
</html>
HTML 表单验证:姓名、邮箱和留言

原文地址: http://www.cveoy.top/t/topic/ZRc 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录