Reputation: 191
I know there are 2-3 similar questions are on site but the mine is very specific. So the situation is, I created a input field that validates a string if it matches /abc/ pattern (regex in javascript). But the output is very unexpected i.e., Even If i provide a input that matches the pattern then output is "Invalid input" and if i provide a input that doesn't matches the pattern then same above output. This is okay but I am unable to figure out what is what is happening when I am providing a valid input?
Here is the code:
<!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>
Upvotes: 1
Views: 75
Reputation: 1493
try using .value instead of .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>
Now if you write "abc" its will works.
Upvotes: 0
Reputation: 639
document.getElementById("1").data
Is not a valid method. You have to use value method to obtain the data inside the input box. Try this code:
<!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: Please do use a bit of debugging tools that the browsers provide.
Upvotes: 3