提交的验证方法(通过单个字符比较):
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> VerifyDate <form id="form1" action="VefifyData.html"> <input type="text" name="d1" /> <input type="submit" /> </form> <script type="text/javascript"> document.getElementById("form1").onsubmit = function chkForm() { var text = this.d1.value; alert(text.length); for (i=0;i<text.length;i++) { alert(i+"的字符是"+text.charAt(i)); if (text.charAt(i) > ‘9‘ || text.charAt(i) < ‘0‘) { alert("第 " + i + " 个为非数字字符 "+text.charAt(i)); } else { alert("第 " + i + " 个为数字字符"+text.charAt(i)); } } return false; } </script> </body> </html>
提交验证方法(通过正则表达式)
js中用pattern.test(需要验证字符串) pattern是正则表达式
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> VerifyDate <form id="form1" action="VefifyData.html"> <input type="text" name="d1" /> <input type="submit" /> </form> <script type="text/javascript"> document.getElementById("form1").onsubmit = function chkForm() { var text = this.d1.value; if(verifyData(text)){ alert("全部为数字..."); return false; }else{ alert("不全部为数字..."); return false; }; } function verifyData(text){ var dataPattern=/^\d[0-9]{0,}$/; return dataPattern.test(text); } </script> </body> </html>
提交之前验证的方法
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> VerifyDate <form id="form1" action="http://www.cnblogs.com/qingyundian" onsubmit="return chkForm()"> <input type="text" id="d1" /> <input type="submit" /> </form> <script type="text/javascript"> function chkForm() { var text = document.getElementById("d1").value; alert(text); if(verifyData(text)){ alert("全部为数字..."); alert("校验成功,之后进行提交..."); return true; }else{ alert("不全部为数字..."); alert("校验失败,不进行提交"); return false; } return false; } function verifyData(text){ var dataPattern=/^\d[0-9]{0,}$/; return dataPattern.test(text); } </script> </body> </html>
这种方法会先校验
校验成功会 返回true 给onsubmit
校验失败会 返回false给onsubmit
校验成功 打开激活网页
原文地址:https://www.cnblogs.com/qingyundian/p/8393483.html
时间: 2024-10-28 14:29:29