I have been working with this problem for some time and was hoping for some guidance. I am prompting the user to enter "course" info (example AAA.111#2222_aa-1234
) I then created a validate function and button for the html page to source from the javascript
Within my isValidInfo function, I can get it to work with:
var infoRegExp = /^(\D{3}.\d{3}#\d{4}_\D{2}-\d{4})$/g;
with the IF statement BUT the else statement does not produce the "Invalid information" message.
Also once I change the code within the function to be case sensitive ie;
/^(\D[A-Z][A-Z][A-Z].\d{3}#\d{4}_\D[a-z][a-z]-\d{4})$/i;
the validate function/button does not work.
<!DOCTYPE html>
<html lang = "en">
<head>
<title>Input Course Info</title>
</head>
<body>
<script src = "course.js"></script>
<button onclick= "validate()">Validate</button>
</body>
</html>
function isValidInfo(course) {
var infoRegExp = /^(\D[A-Z][A-Z][A-Z].\d{3}#\d{4}_\D[a-z][a-z]-\d{4})$/i;
var result = infoRegExp.test(course);
return result
}
var course = prompt("Enter course information (format: AAA.111#2222_aa-1234): ");
function validate(){
if (isValidInfo(course)) {
document.write("Valid information!");
} else {
documwnt.write("Invalid information.")
}
}
I need to be able to click the validate button a produce either a "Valid information!" message or an "Invalid information." message. Any helpful guidance would be appreciated. Right now with the code as is, the validate button does nothing. Removing the [AZ]... and [az] and changing the 'i' to a 'g' gets it to work if I enter aaa.111#2222_aa-1234, but anything ELSE does not produce a message sighting invalid info.
You may use
function isValidInfo(course) { var infoRegExp = /^[AZ]{3}\\.\\d{3}#\\d{4}_[az]{2}-\\d{4}$/i; // Remove i flag if aaa.111#2222_aa-1234 is invalid! var result = infoRegExp.test(course); return result } var course = prompt("Enter course information (format: AAA.111#2222_aa-1234): "); function validate(){ if (isValidInfo(course)) { return "Valid information!"; } else { return "Invalid information."; } } console.log(validate(course));
The regex demo is available here . Note that validate()
function should be called with your course
argument, hence I added validate(course)
in the console.log()
.
Also, see the regex graph :
Details
^
- start of string [AZ]{3}
- three letters (case insensitive modifier makes it match lowercase letters, too) \\.
- a dot \\d{3}
- three digits #
- a #
char \\d{4}
- four digits _
- an underscore [az]{2}
- any 2 letters -
- a hyphen \\d{4}
- four digits (case insensitive modifier makes it match lowercase letters, too) $
- end of string.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.