javascript html5实现表单验证
表单验证为终端用户检测无效的数据并标记这些错误,是一种用户体验的优化。
下面展现浏览器自带的验证功能也可在移动端中查看:
HTML部分:
<!DOCTYPEhtml> <htmllang="en"> <head> <metacharset="UTF-8"> <metaname="viewport"content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0"> <title>html5表单验证</title> </head> <body> <formaction="#"id="formValid"class="myform"novalidate="novalidate"onsubmit="returncheckForm()"> <fieldset> <divclass="form-group"> <labelfor="name">名称</label> <div> <inputtype="text"class="form-control"id="name"name="name"required/> <spanclass="form-error">不能为空</span> </div> </div> <divclass="form-group"> <labelfor="email">邮箱</label> <div> <inputtype="email"class="form-control"id="email"name="email"required/> <spanclass="form-error">邮箱格式不正确</span> </div> </div> <divclass="form-group"> <label>省份</label> <selectname="province"class="form-control"> <optionvalue="">请选择</option> <optionvalue="s">四川</option> <optionvalue="c">重庆</option> </select> </div> <inputtype="submit"class="btn"value="提交"/> </fieldset> </form> </body> </html>
CSS部分:
fieldset{border:0;} .myform.form-control{ display:block; padding:5px; width:100% } .myforminput:focus:invalid+.form-error{ display:inline; } .myform.form-error{ display:none; position:absolute; margin-top:.7em; padding:1px2px; 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:.5emsolid#f40; border-right:.5emsolidtransparent; border-left:.5emsolidtransparent; border-top:0dotted; transform:rotate(360deg); overflow:hidden; } .btn{ padding:5px20px; }
JavaScript部分:
functioncheckForm(){ varmyform=document.getElementById("formValid"); returncheck(myform.elements); } functioncheck(eles){ varele; for(vari=0;i<eles.length;i++){ ele=eles[i]; if(ele.nodeName=="SELECT"){ if(!ele.selectedIndex){ alert("请选择省份"); returnfalse; } }elseif(ele.name){ if(!ele.checkValidity()){ ele.focus(); returnfalse; } } } returntrue; }
以上就是javascript结合html5实现表单验证的全部代码,希望对大家的学习有所帮助。