我正在尝试验证电子邮件地址和邮政编码,但这似乎不起作用?
我使用button onClick="validateForm()"
,我应该使用input type="button"
吗?它会有所作为吗?
function validateForm() {
var x = document.getElementById("e1").value;
var atpos = x.indexOf("@");
var r1 = false;
var dotpos = x.lastIndexOf(".");
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= x.length) {
alert("Not a valid e-mail address");
} else {
r1 = true;
}
var patt = /[0-9]/g;
var zipc = document.getElementById("u1").value;
var result = zipc.match(patt);
if (result && r1) {
alert("Pattern matches for both");
} else {
alert("Pattern doesnt match");
}
}
答案 0 :(得分:0)
它对我来说很好:https://jsfiddle.net/q4Lkkps4/
<input id="e1" type="text" />
<input id="u1" type="text" />
<button onclick="validateForm();">go</button>
<script>
function validateForm() {
var x = document.getElementById("e1").value;
var atpos = x.indexOf("@");
var r1 = false;
var dotpos = x.lastIndexOf(".");
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= x.length) {
alert("Not a valid e-mail address");
} else {
r1 = true;
}
var patt = /[0-9]/g;
var zipc = document.getElementById("u1").value;
var result = zipc.match(patt);
if (result && r1) {
alert("Pattern matches for both");
} else {
alert("Pattern doesnt match");
}
}
</script>
虽然您所说的错误来自https://jsfiddle.net/dkyL41gr/
<script type="text/javascript">//<![CDATA[
window.onload=function(){
function validateForm() {
var x = document.getElementById("e1").value;
var atpos = x.indexOf("@");
var r1 = false;
var dotpos = x.lastIndexOf(".");
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= x.length) {
alert("Not a valid e-mail address");
} else {
r1 = true;
}
var patt = /[0-9]/g;
var zipc = document.getElementById("u1").value;
var result = zipc.match(patt);
if (result && r1) {
alert("Pattern matches for both");
} else {
alert("Pattern doesnt match");
}
}
}//]]>
</script>
<body>
<input id="e1" type="text">
<input id="u1" type="text">
<button onclick="validateForm();">go</button>
</body>
也许您以错误的方式使用脚本标记。
请在此粘贴测试代码。