I have to validate a user input for a course code. The code must be:
So far I've got something like this:
var inputMessage = "Please enter valid course code";
var userInput = " ";
userInput = prompt (inputMessage);
while (userInput.length !=7 || userInput.slice(-4)<1000 || userInput.slice(-4)>9999)
{
alert ("Invalid Course Code. Please try again");
userInput = prompt(inputMessage);
}
Any help would be great. I am struggling with the alpha + the no spaces/symbols.
Below example will help you to do that in Java.
import java.util.Scanner;
import java.util.regex.Pattern;
public class RegexSample {
public static boolean checkPass(String s) {
Pattern p = Pattern.compile("[A-Z]{3}[0-9]{4}");
return p.matcher(s).find();
}
public static void main(String[] args) {
String inputMessage = "Please enter valid course code";
String userInput = " ";
Scanner input = new Scanner(System.in);
System.out.println(inputMessage);
userInput = input.nextLine();
while (userInput.length() != 7 || !checkPass(userInput)) {
System.out.println("Invalid Course Code. Please try again");
userInput = input.nextLine();
}
System.out.println("Input Validated");
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With