[英]Validating HTML form using JavaScript
我知道现场有2-3个类似的问题,但矿井非常具体。 所以情况是,我创建了一个输入字段,如果匹配/ abc / pattern(javascript中的正则表达式),则验证字符串。 但输出是非常意外的,即,如果我提供与模式匹配的输入,则输出为“无效输入”,如果我提供的输入与模式不匹配,则输出相同。 这没关系,但我无法弄清楚当我提供有效输入时会发生什么?
这是代码:
<!DOCTYPE html>
<html>
<head>
<title>form validation</title>
</head>
<body>
<script>
function check() {
var field = document.getElementById("1").data;
var regex = /abc/;
if(regex.test(field) === true)
document.getElementById("2").innerHTML="Input accepted";
else
document.getElementById("2").innerHTML="Invalid input!";
}
</script>
First field:<br />
<input type="text" id="1"> <span id="2"></span> <br />
<button type="submit" onclick="check();">Validate</button>
</body>
</html>
document.getElementById("1").data
不是有效的方法。 您必须使用value方法来获取输入框内的数据。 试试这段代码:
<!DOCTYPE html>
<html>
<head>
<title>form validation</title>
</head>
<body>
<script>
function check() {
var field = document.getElementById("1").value;
var regex = /abc/;
if(regex.test(field) === true)
document.getElementById("2").innerHTML="Input accepted";
else
document.getElementById("2").innerHTML="Invalid input!";
}
</script>
First field:<br />
<input type="text" id="1"> <span id="2"></span> <br />
<button type="submit" onclick="check();">Validate</button>
</body>
</html>
PS:请使用浏览器提供的一些调试工具。
尝试使用.value而不是.data
<script>
function check() {
var field = document.getElementById("1").value; //<--- here
var regex = /abc/;
if(regex.test(field) === true)
document.getElementById("2").innerHTML="Input accepted";
else
document.getElementById("2").innerHTML="Invalid input!";
}
</script>
现在,如果你写“abc”,它将起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.