网站用户提交姓名和电话号码表单验证JS
时间:2023年11月28日
/来源:网络
/编辑:佚名
网站一个用户留信息的表单,功能是表单有2个字段一个是姓名,一个是电话号码,用户提交表单后,JS验证姓名字段是否为空,电话号码字段验证填写的是不是电话号码格式。
<form>
<label for="name">姓名:</label>
<input type="text" id="name" name="name">
<br>
<label for="phone">电话号码:</label>
<input type="tel" id="phone" name="phone">
<br>
<input type="submit" value="提交">
</form>
<script>
const nameInput = document.getElementById('name');
const phoneInput = document.getElementById('phone');
const form = document.querySelector('form');
form.addEventListener('submit', function(event) {
if (nameInput.value === '') {
alert('姓名不能为空');
event.preventDefault();
} else if (!phoneInput.value.match(/^\d{11}$/)) {
alert('电话号码格式不正确');
event.preventDefault();
} else {
// 验证通过,表单数据可以被提交到服务器端进行处理
}
});
</script>
<form>
<label for="name">姓名:</label>
<input type="text" id="name" name="name">
<br>
<label for="phone">电话号码:</label>
<input type="tel" id="phone" name="phone">
<br>
<input type="submit" value="提交">
</form>
<script>
const nameInput = document.getElementById('name');
const phoneInput = document.getElementById('phone');
const form = document.querySelector('form');
form.addEventListener('submit', function(event) {
if (nameInput.value === '') {
alert('姓名不能为空');
event.preventDefault();
} else if (!phoneInput.value.match(/^\d{11}$/)) {
alert('电话号码格式不正确');
event.preventDefault();
} else {
// 验证通过,表单数据可以被提交到服务器端进行处理
}
});
</script>
新闻资讯 更多
- 【建站知识】查询nginx日志状态码大于400的请求并打印整行04-03
- 【建站知识】Python中的logger和handler到底是个什么?04-03
- 【建站知识】python3拉勾网爬虫之(您操作太频繁,请稍后访问)04-03
- 【建站知识】xpath 获取meta里的keywords及description的方法04-03
- 【建站知识】python向上取整以50为界04-03
- 【建站知识】scrapy xpath遇见乱码解决04-03
- 【建站知识】scrapy爬取后中文乱码,解决word转为html 时cp1252编码问题04-03
- 【建站知识】scrapy采集—爬取中文乱码,gb2312转为utf-804-03