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

2 Answers 2

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");
}
Sign up to request clarification or add additional context in comments.

Comments

-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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.