Home > Software design >  Java validation vehicle registration
Java validation vehicle registration

Time:10-19

I'm trying to do a simple validation for vehicle registration number.

  • It must include "-" Dash/Hyphen symbol. Example: BIR - 5698

  • It allows Numbers/Letters and Hyphen symbol only.

  • All the other symbols are invalid. ( `~!@#$%^&*()_ =./;,<>":|[]{} )

    My code -

     public static void main(String[] args) {
    
     Scanner in = new Scanner(System.in);
     if (in.hasNext("[A-Za]")) {
         System.out.println("Vehicles :"   vehicles );
     }else {
         System.out.println("Enter a Valid Value");
    

Thank you. Your kind help highly appreciated.

CodePudding user response:

Add all valid characters:

if (in.hasNext("[A-Za-z0-9\-]")) {

CodePudding user response:

I'm not sure if what you show as an example registration number is the actual format for a vehicle registration number (3 chars, a dash, 4 chars). Does the whitespace before and after the dash need to be there or is that optional? Are there only three alphanumeric characters before the dash and always 4 alphanumeric character after the dash? Because you haven't indicated as such either way I'm going to assume so. The supplied Regular Expression below can be easily modified to accommodate whatever format(s) are required.

Here is the code:

String ls = System.lineSeparator();
Scanner in = new Scanner(System.in);
String vrn = "";
while (vrn.isEmpty()) {
    System.out.print("Please enter a valid Vehicle Registration number"   ls 
                     "or 'q' to quit: -> ");
    vrn = in.nextLine().trim();
    if (vrn.equalsIgnoreCase("Q")) { //Quit?
        return;
    }
        
    // Validate entry...
    if (!vrn.matches("(?i)[A-Z0-9]{3} ?\\- ?[A-Z0-9]{4}")) {
        System.out.println("Invalid Vehicle Registation Number! (" 
                     vrn   ") Try again..."   ls);
        vrn = ""; // Empty vrn so to re-loop.
    }
}
System.out.println("VALID VRN!");

About the Regular Expression (regex):

  • (?i) Letter case insensitive;
  • [A-Z0-9]{3} Any 3 alphanumeric character (A to Z, a to z, or 0 to 9) before the dash;
  • ? An optional single whitespace before the mandatory dash (-);
  • \\- A mandatory single literal Dash character;
  • ? An optional single whitespace after the mandatory dash (-);
  • [A-Z0-9]{4} Any 4 alphanumeric characters (A to Z, a to z, or 0 to 9) after the dash;

If you want to change the number of allowable characters within the regex then you can consider any one of these few examples:

  • {3} Strictly 3 characters allowed only;
  • {3,6} Strictly 3 to 6 characters allowed only;
  • {3,} 3 or more characters allowed;
  • `{0,} 0 or more characters allowed.
  • Related