首页 / HTML5 / html5新增的客户端校验
html5新增的客户端校验
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了html5新增的客户端校验,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1916字,纯文字阅读大概需要3分钟。
内容图文
![html5新增的客户端校验](/upload/InfoBanner/zyjiaocheng/1174/7278799fbf734339aba860c82ec8a87c.jpg)
1.表单控件提供的checkValidity()方法进行校验。
例如:如果checkValidity()方法返回true
则表明该表单内的所有表单控件都有效。
< body > < form action ="" > 生日: < input id ="birth" name ="birth" type ="date" >< br > 邮件地址: < input type ="email" id ="email" name ="email" >< br > < input type ="submit" value ="提交" onclick ="return check()" > </ form > < script > var check = function () { return commonCheck( ‘ birth ‘ , ‘ 生日 ‘ , ‘ 字段必须是有效的日期 ‘ ) && commonCheck( ‘ email ‘ , ‘ 邮箱 ‘ , ‘ 字段必须符合电子邮件的格式 ‘ ) } var commonCheck = function (fieid, fieName, tip) { var targetEle = document.getElementById(fieid); if (targetEle.value.trim() == ‘‘ ) { alert(fieName + ‘ 字段必须填写 ‘ ); return false } else if ( ! targetEle.checkValidity()) { alert(fieName + tip); return false } return true } </ script > </ body >
2.自定义验证 应用h5新增的setCustomValidity()方法实现。只有当该表单没有通过校验时才能调用该方法。
例如:
< body > < form action ="" > 图书名: < input id ="name" name ="name" type ="text" required >< br > 图书ISBN: < input type ="text" id ="isbn" name ="isbn" required pattern ="\d{3}-\d-\d{3}-\d{5}" >< br > 图书价格: < input type ="number" id ="price" name ="price" required min ="20" max ="150" step ="5" >< br > < input type ="submit" value ="提交" onclick ="check()" > </ form > < script > var check = function () { if ( ! document.getElementById( ‘ name ‘ ).checkValidity()){ document.getElementById( ‘ name ‘ ).setCustomValidity( ‘ 图书名是必须的 ‘ ); } if ( ! document.getElementById( ‘ isbn ‘ ).checkValidity()){ document.getElementById( ‘ isbn ‘ ).setCustomValidity( ‘ 图书isbn是必须的 ‘ + ‘ \n而且必须符合xxx-x-xxx-xxxxx的格式(其中x代表数字) ‘ ); } if ( ! document.getElementById( ‘ price ‘ ).checkValidity()){ document.getElementById( ‘ price ‘ ).setCustomValidity( ‘ 价格是必须的 ‘ + ‘ \n而且必须在20-150之间,且是5的倍数 ‘ ); } } </ script >
原文:http://www.cnblogs.com/athean/p/6696452.html
内容总结
以上是互联网集市为您收集整理的html5新增的客户端校验全部内容,希望文章能够帮你解决html5新增的客户端校验所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。