一、简概

因为,前端经常涉及到表单验证,故此篇博客用于记录前端JS对表单验证的方法。

通过表单验证,当对form表单提交时,可以防止不合法的数据传递至后台(以及判空操作)。这里我们先定义一个表单,作为示例,其它的情况都可以此类推。

示例表单

前端表单代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<div>
<form method="get" action="https://www.baidu.com" id="form">
<table align="center" style="margin: 0 auto;">
<tr>
<td><label>用户名</label></td>
<td><input type="text" name="username" placeholder="请输入用户名" style="width: 150px" id="username"></td>
</tr>
<tr>
<td><label>邮箱</label></td>
<td><input type="email" name="email" placeholder="请输入邮箱" style="width: 150px" id="email"></td>
</tr>
<tr>
<td><label>性别</label></td>
<td align="left">
<input type="radio" name="male" value="male" checked>
<input type="radio" name="female" value="female">
</td>
</tr>
<tr>
<td><label>出生日期</label></td>
<td><input type="date" name="birthday" style="width: 150px" id="birthday"></td>
</tr>
<tr>
<td align="center" colspan="2">
<input type="submit" name="register" value="注册" style="margin-top: 5px">
</td>
</tr>
</table>
</form>
</div>

前端进行表单验证只需作用在两个地方即可:

  1. 绑定当前需要验证的input标签的离焦事件。

  2. form表单的submit进行全部的input标签判定

    当结果全部返回true才能进行提交,否则无法提交。