0

I have an HTML file and an external JavaScript file. I have input from the user in the HTML and on the click on the validate button, the courseValidation() function is called. The problem is with the if statement. When the input does not match myRegExp, it should write that the format is incorrect to the page, but it always writes Correct Format, regardless if it is correct or not. Not sure what I am doing wrong. I'm just learning so no negative comments please.

HTML File:

<html lang="en">
<head>
<title>Validation</title>
</head>
<body>
    <script src="course.js"></script>
    <p>Enter Course Information:</p>

    <input id="courseCode" type="text">
    <button onclick="courseValidation()">Validate</button>

        <p id="course"></p>
   </body>
</html>

External JavaScript File:

function courseValidation() {
var courseCode = document.getElementById("course").innerHTML;
var myRegExp = /\D{3}.\d{3}#\d{4}_\D{2}-\d{4}/;

if (courseCode.match(myRegExp)) {
    document.write("Incorrect Format");
} else {
    document.write("Correct Format");
}
}
  • 1
    Possible duplicate of [How to get an input text value in JavaScript](https://stackoverflow.com/questions/11810874/how-to-get-an-input-text-value-in-javascript) – Oghli Jun 18 '17 at 23:34

2 Answers2

2

You are not retrieving the value of the input correctly. var courseCode = document.getElementById("course").innerHTML; should be var courseCode = document.getElementById("courseCode").value;.

Also, your if statement is the wrong way around. It should read:

if (courseCode.match(myRegExp)) {
    document.write("Correct Format");
} else {
    document.write("Incorrect Format");
}
Wayne Allen
  • 1,605
  • 1
  • 10
  • 16
-1

The ID of your input is courseCode not course and you are using .innerhtml, it should be .value

var courseCode = document. getElementById('courseCode).value

dealwap
  • 621
  • 2
  • 14
  • 33