java Html&JavaScript面试题:HTML 的 form 提交之前如何验证数值文本框的内容全部为数字? 否则的话提示用户并终止提交?
2024-10-16 19:54:06
提交的验证方法(通过单个字符比较):
<!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
校验成功 打开激活网页
最新文章
- iOS项目常用效果方法注意点集锦
- spring常用注解
- i2c协议简要分析(转载)
- 为Mac Terminal设置代理
- asp.net 服务器Button控件使用(onclick和onclientclick使用)
- Chrome谷歌浏览器首页被改为Hao123导航怎么办|附各类解决方法【转】
- struts2与struts1整合,java.lang.InstantiationException, Exception occurred during processing request: null
- C#学习(三)
- PyQuery查询html信息
- Spring BeanFactory实例化Bean的详细过程
- php 进行跨域操作
- centos查看自启动服务
- 20175316盛茂淞 2018-2019-2 《Java程序设计》第7周学习总结
- word转PDF,PDF转Image,使用oppenOffice注意事项等
- SSH原理及操作
- ubuntu服务器配置
- Latex 三线表及设置列数
- CNN卷积层基础:特征提取+卷积核+反向传播
- hehe,网易邮箱已经流氓到这个地步了
- 详述MySQL服务在渗透测试中的利用