表单验证为终端用户检测无效的数据并标记这些错误,是一种用户体验的优化。
下面展现浏览器自带的验证功能也可在移动端中查看:
HTML部分:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0"> <title>html5 表单验证</title> </head> <body> <form action="#" id="formValid" novalidate="novalidate" onsubmit="return checkForm()"> <fieldset> <div> <label for="name">名称</label> <div> <input type="text" id="name" name="name" required/> <span>不能为空</span> </div> </div> <div> <label for="email">邮箱</label> <div> <input type="email" id="email" name="email" required/> <span>邮箱格式不正确</span> </div> </div> <div> <label>省份</label> <select name="province"> <option value="">请选择</option> <option value="s">四川</option> <option value="c">重庆</option> </select> </div> <input type="submit" value="提交"/> </fieldset> </form> </body> </html>
CSS部分:
fieldset{border: 0;} .myform .form-control{ display: block; padding: 5px; width: 100% } .myform input:focus:invalid + .form-error{ display: inline; } .myform .form-error{ display: none; position: absolute; margin-top: .7em; padding: 1px 2px; color: #fff; font-size: .875rem; background: #f40; } .myform .form-error:after{ position: absolute; content: ""; top: -.5em; left: .5em; z-index: 100; display: inline-block; width: 0; height: 0; vertical-align: middle; border-bottom: .5em solid #f40; border-right: .5em solid transparent; border-left: .5em solid transparent; border-top: 0 dotted; transform: rotate(360deg); overflow: hidden; } .btn{ padding: 5px 20px; }
JavaScript部分:
function checkForm(){ var myform = document.getElementById("formValid"); return check(myform.elements); } function check(eles){ var ele; for(var i = 0;i<eles.length;i++){ ele = eles[i]; if(ele.nodeName == "SELECT"){ if(!ele.selectedIndex){ alert("请选择省份"); return false; } }else if(ele.name){ if(!ele.checkValidity()){ ele.focus(); return false; } } } return true; }
以上就是javascript结合html5实现表单验证的全部代码,希望对大家的学习有所帮助。
【javascript html5实现表单验证】相关文章:
★ JavaScript基于setTimeout实现计数的方法