Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validating a user input

I have to validate a user input for a course code. The code must be:

  • A length of 7
  • First 3 characters are upper case alphabetic
  • Last four are numeric between 1000 and 9999
  • No spaces nor symbols.

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.

like image 203
Mitchell Pearce Avatar asked Sep 25 '26 01:09

Mitchell Pearce


1 Answers

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");

    }

}
like image 52
Ganesh S Avatar answered Sep 27 '26 16:09

Ganesh S