HTML 表单验证概述
HTML 表单验证概述
当前只要稍微规范一些的网站,在提交表单信息的时候都会进行格式验证。
比如验证用户名密码是否为空、邮箱格式是否正确,或者身份证格式是否规范。
通常表单验证分为两层:
(1).前端表单验证,与用户有良好的交互界面,但是并不安全,因为JavaScript可以被禁用。
(2).后台表单验证,除了前端的验证以外,为了保证安全,后台代码还会进行一层验证。
本文并不关心后台是如何实现验证的,只介绍前台实现的验证功能。
首先看一段代码实例:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.dandelioncloud.cn/" />
<title>蒲公英云</title>
<script type="text/javascript">
function checkForm(form) {
let reg = /^([\.a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;
if(form.username.value == "") {
alert("用户名不能为空!");
form.username.focus();
return false;
}
if(form.password.value == "") {
alert("密码不能为空!");
form.password.focus();
return false;
}
if(form.email.value==""){
alert("邮箱不能为空!");
form.email.focus();
return false;
}else if(!reg.test(form.email.value)){
alert("邮箱格式不正确!");
form.email.focus();
return false;
}
return true;
}
window.onload = function () {
var myform = document.forms[0];
myform.onsubmit = function () {
return checkForm(this);
}
}
</script>
</head>
<body>
<form action="#" method="post">
姓名:<input type="text" name="username"/><br/>
密码:<input type="password" name="password" /><br/>
邮箱:<input type="text" name="email" /><br/>
<input type="submit" value="提交表单"/>
</form>
</body>
</html>
上述代码利用JavaScript实现了表单验证功能。
代码分析如下:
(1).点击提交按钮之后,会对表单元素内容进行正确性验证。
(2).对用户名和密码进行value是否为空验证,对邮箱同时进行是否为空和邮箱格式验证。
HTML5之前,前端表单验证必须要结合JavaScript,技术的进步通常是为了满足人懒惰的天性,HTML5也体现了这一点,大量简单的表单验证效果是HTML5内置,无需我们书写JavaScript代码。
代码演示如下:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.dandelioncloud.cn/" />
<title>蒲公英云</title>
</head>
<body>
<form action="#" method="post">
姓名:<input type="text" name="username" required/><br/>
密码:<input type="password" name="password" required /><br/>
邮箱:<input type="email" name="email" required /><br/>
<input type="submit" value="提交表单"/>
</form>
</body>
</html>
上述代码没有一段JavaScript代码,但是实现了比较良好的表单验证功能。
代码分析如下:
(1).表单元素value值不为空,那么只要在对应元素添加required属性即可。
(2).如果要实现邮箱格式验证,只要将type属性值修改为email。
最后总结:
虽然HTML5自带的表单验证功能极大提高了工作效率,然而往往免费的东西不是最好的。
所以在一些验证需求要求较高的情况下,还需要进行自定义。
还没有评论,来说两句吧...