HTML5表单验证给前端人员带来了便利,但是在用户体验上存在一些缺陷,默认的提示对用户很不友好,无法准确的获取想要的信息。好在大牛们在接口设计的时候提供了setCustomValidilty方法可以自定义提示信息。这是一个好消息,但也存在一些弊端,需要让开人员做额外的一些处理才达到真正想要的目的。
接下来通过以下示例来阐述方法的应用。
未调用setCustomValidity()方法
<!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}[ DISCUZ_CODE_21 ]quot; placeholder="请输入代码" > <button type="submit">Check</button> </form> </body> </html>
|
复制代码
执行结果:
A:未输入数据

B:不匹配

这两个结果都匹配了。但是不匹配这里的提示方案案与预想的不符合。
通过调用setCustomValidity方法来优化提示文案
<!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}[ DISCUZ_CODE_22 ]quot; placeholder="请输入代码" > <button type="submit">Check</button> </form> <script type="text/javascript"> document.querySelector("input").setCustomValidity("请输入4位数字的代码"); </script> </body> </html>
|
复制代码
执行结果:
A:为空

B:不合法

C:合法

从三个操作来看,调用了setCustomValidity方法后,原生的表单验证罗辑都返回false了。悲剧。
再看看接口属性的变化
调用之前:
A)

B)

C)

调用之后:
A)


B)


C)


从上面的截图可以看到validationMessage没清空,valueMissing和patternMismatch都已经验证通了。
总结一下:
从面上可以看出,验证通过与否除了跟validity接口下的属性相关外,还跟validationMessage是否有值有关系。只有当validity接口下的属性(customError除外)都为false并且validationMessage为空时才算验证通过。
优化后的代码:
<!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}[ DISCUZ_CODE_23 ]quot; 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>
|