JavaScript函数--"check"

JS中一个较常见的函数"checkForm"。是用来检验表单信息的正确性。

步骤如下:

1:表单<form>添加提交事件

<form action="#" method="get" name="regForm" οnsubmit="return checkForm()">

</form>

添加οnsubmit="return checkForm()" 其中红色函数名字随意。

2:在表中<td>添加id字段

<td>用户名</td>
<td>
<input type="text" name="user" id="user"/>
</td>

3 : 编写check()函数,进行校验

<scrtipt>

//1用户名不能为空

var uValue = document.getElementById("user").value;

if(uValue==""){

alter("用户名不能为空");

return false;

}

</scrtipt>

其中绿色字段与<td>中必须相同。

简单的案例:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>注册页面</title>
<script>
/*检查表单函数*/
function checkForm(){
//alert("aa");
//1 获取用户输入的数据
var uValue = document.getElementById("user").value;
if(uValue==""){
//2给出错误信息
alert("用户名不能为空!");
return false;
}

/*校验密码*/
var pValue = document.getElementById("password").value;
if(pValue==""){
alert("密码不能为空!");//
return false;
}

/*校验确认密码*/
var rpValue = document.getElementById("repassword").value;
if(rpValue!=pValue){
alert("两次密码输入不一致!");
return false;
}

/*校验邮箱地址*/
var eValue = document.getElementById("email").value;
if(!/^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/.test(eValue)){
alert("邮箱地址不对!");
return false;
}
}
</script>
</head>
<body>
<table>
<!-- 1 logo部分 -->
<tr>
<td>
<table>
<tr>
<td>
StevenLu SHOP
</td>
<td>
<a href="#">登入</a>
<a href="#">注册</a>
<a href="#">购物车</a>
</td>
</tr>
</table>
</td>
</tr>
<!-- 2 导航部分 -->
<tr>
<td >
<a herf="#">
<font size="5" color="whirte">首页</font>
</a>
<a herf="#">
<font size="5" color="whirte">手机数码</font>
</a>
<a herf="#">
<font size="5" color="whirte">电脑办公</font>
</a>
<a herf="#">
<font size="5" color="whirte">家用电器</font>
</a>
</td>
</tr>
<!-- 3 注册列表 -->
<tr>
<form action="#" method="get" name="regForm" οnsubmit="return checkForm()">
<table>
<tr height="40px">
<td colspan="2">
<font size="4">会员注册</font>
</td>
</tr>
<tr>
<td>用户名</td>
<td>
<input type="text" name="user" id="user"/>
</td>
</tr>
<tr>
<td>密码</td>
<td>
<input type="password" name="password" id="password"/>
</td>
</tr>
<tr>
<td>确认密码</td>
<td>
<input type="repassword" name="password" id="repassword"/>
</td>
</tr>
<tr>
<td>Email</td>
<td>
<input type="text"/ name="email" id="email">
</td>
</tr>
<tr>
<td>性别</td>
<td>
<input type="radio" name="sex" value="男"/>男
<input type="radio" name="sex" value="女"/>女
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="注册"/>
</td>
</tr>
</table>
</form>
</tr>
</table>
<!-- 版权 -->
<td align="center">
<p>Copyright @2018.6.27 StevenLu</p>
</td>
</body>

</html>

posted @ 2022-11-15 23:42  一统天下。  阅读(631)  评论(0编辑  收藏  举报