java Html&JavaScript面试题:HTML 的 form 提交之前如何验证数值文本框的内容全部为数字? 否则的话提
提交的验证方法(通过单个字符比较):
<!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
校验成功 打开激活网页