当前位置: 移动技术网 > IT编程>开发语言>JavaScript > JS函数checkForm检验表单信息正确性的方法教程

JS函数checkForm检验表单信息正确性的方法教程

2018年10月07日  | 移动技术网IT编程  | 我要评论

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

步骤如下:

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

<form action="#" method="get" name="regform" onsubmit="return checkform()">

</form>

添加onsubmit="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;

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" onsubmit="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>

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网