HTML5+setCutomValidity()函数验证表单实例分享
HTML5表单验证给前端人员带来了便利,但是在用户体验上存在一些缺陷,默认的提示对用户很不友好,无法准确的获取想要的信息。好在大牛们在接口设计的时候提供了setCustomValidilty方法可以自定义提示信息。这是一个好消息,但也存在一些弊端,需要让开人员做额外的一些处理才达到真正想要的目的。
示例一:
<!DOCTYPE HTML> <head> <meta charset="UTF-8"> <title>Html5页面使用javascript验证表单判断输入</title> <script language="javascript"> function check(){ var pass1=document.getElementbyid("pass1"); var pass2=document.getElementbyid("pass2"); if (pass1.value!=pass2.value){ pass2.setCustomvalidity("密码不一致"); else pass2.setCustomvalidity(""); } var email=document.getElementbyid("email"); if (!email.checkValidity()) email.setCustomvalidity("请输入正确的email地址"); } </script> </head> <form id="testForm" onsubmit="return check()"> 密码:<input type="password" name="pass1" id="pass1" /><br/> 确认密码:<input type="password" name="pass2" id="pass2" /><br/> Email:<input type="email" name="email" id="email" /><br/> <input type="submit" /> </form>
示例二:
<!DOCTYPE html> <html> <head> <mata charset="utf-8"> <title>form test</title> </head> <body> <form name="test" action="." method="post"> <input type="text" required pattern="^\d{4}$" oninput="out(this)" placeholder="请输入代码" > <button type="submit">Check</button> </form> <script type="text/javascript"> function out(i){ var v = i.validity; if(true === v.valueMessing){ i.setCustomValidity("请填写些字段"); }else{ if(true === v.patternMismatch){ i.setCustomValidity("请输入4位数字的代码"); }else{ i.setCustomValidity(""); } } } </script> </body> </html>
以上所述就是本文的全部内容了,希望大家能够喜欢。
相关推荐
nercon 2020-07-26
WangJiangNan 2020-01-07
typhoonpython 2019-11-03
renpinghao 2019-11-03
谷歌架构师 2016-04-15
tztzyzyz 2020-07-20
nercon 2020-07-16
hzyuhz 2020-06-28
xustart0 2020-06-14
YAruli 2020-06-13
Kakoola 2020-05-17
ThinkingLink 2020-05-16
85443563 2020-04-30
xcguoyu 2020-03-04
somboy 2020-03-03
Elements小帅 2020-01-16