写一个验证表单包括JS,用户名称,邮件地址,联系电话
时间: 2024-06-10 20:05:35 浏览: 10
好的,为了方便理解,我先将这个问题拆分成三个小问题来回答:
1. 如何编写一个表单HTML代码?
您可以使用HTML5中的form元素来创建表单,并在form元素中添加一些表单控件,如input、textarea、select、radio等,代码示例如下:
```
<form>
<label for="username">用户名:</label>
<input type="text" id="username" name="username"><br>
<label for="email">邮件地址:</label>
<input type="email" id="email" name="email"><br>
<label for="phone">联系电话:</label>
<input type="tel" id="phone" name="phone"><br>
<button type="submit">提交</button>
</form>
```
2. 如何使用JS进行表单验证?
您可以使用JavaScript中的表单验证方法来验证用户输入的信息是否合法,如下:
```
function validateForm() {
var username = document.getElementById("username").value;
var email = document.getElementById("email").value;
var phone = document.getElementById("phone").value;
if (username == "") {
alert("用户名不能为空");
return false;
}
if (email == "" || !/\S+@\S+\.\S+/.test(email)) {
alert("邮件地址格式不正确");
return false;
}
if (phone == "" || !/^1[0-9]{10}$/.test(phone)) {
alert("联系电话格式不正确");
return false;
}
alert("表单验证通过");
return true;
}
```
3. 如何将JS与HTML表单代码结合起来?
您可以在HTML代码中添加一个按钮,通过JavaScript来绑定表单验证方法,如下:
```
<form>
<label for="username">用户名:</label>
<input type="text" id="username" name="username"><br>
<label for="email">邮件地址:</label>
<input type="email" id="email" name="email"><br>
<label for="phone">联系电话:</label>
<input type="tel" id="phone" name="phone"><br>
<button type="button" onclick="validateForm()">提交</button>
</form>
```
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![text/plain](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)