Reputation: 25
I want to validate an html form using regex for this example pattern: AAA.111#2222_aa-1234
Currently my code is either returning "correct" for all input or "incorrect" for all input, and I cannot figure out where my issue is.
var x = document.getElementById("myForm");
function regExp(courseNum) {
var vCourse = /([A-Z]{3})\.(\d{3})#(\d{4})_([a-z]{2})-(\d{4})/;
return (vCourse.test(courseNum));
}
function isValid() {
if (regExp(x)) {
document.getElementById("demo").innerHTML = "Correct Format";
} else {
document.getElementById("demo").innerHTML = "Incorrect Format";
}
}
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
</head>
<body>
<h3>Please enter your course number below</h3>
<form id="myForm">
Course: <input type="text" name="course" id="course"><br>
</form>
</br>
<button onclick="isValid()">Validate</button>
<p id="demo"></p>
<script src="course.js"></script>
</body>
</html>
I'm in the middle of a javascript course and haven't covered many javascript concepts yet, so I'd like to use the knowledge we have covered up to this point.
Any help with this is greatly appreciated!
Upvotes: 2
Views: 1606
Reputation: 3893
You are very close! Just two changes to get things working. First you are selecting your form to get the value of. You want to select the input instead so change "myForm"
to "course"
. The second thing is that you need to get the value of the input. Right now you are trying to validate the DOM element itself, but you should be validating the value
property of the input element. So change regExp(x)
to regExp(x.value)
.
var x = document.getElementById("course"); // First Change
function regExp(courseNum) {
var vCourse = /([A-Z]{3})\.(\d{3})#(\d{4})_([a-z]{2})-(\d{4})/;
return (vCourse.test(courseNum));
}
function isValid() {
if (regExp(x.value)) { // Second Change
document.getElementById("demo").innerHTML = "Correct Format";
} else {
document.getElementById("demo").innerHTML = "Incorrect Format";
}
}
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
</head>
<body>
<h3>Please enter your course number below</h3>
<form id="myForm">
Course: <input type="text" name="course" id="course"><br>
</form>
</br>
<button onclick="isValid()">Validate</button>
<p id="demo"></p>
<script src="course.js"></script>
</body>
</html>
Upvotes: 4