In some tests, users need to test valid US zip codes by using regular
expressions. Zip code validation may be needed when locating elements
in the html tag or on the UI. This article explains how to validate US
zip code regular expression pattern in Java code. The most commonly
used zip code pattern is:
Regular Expression Pattern: \b[0-9]{5}(?:-[0-9]{4})?\b
Explanation: (explanation syntax is from http://regex101.com)
Here is the Java source code to validate the US Zip Code regular expression
Step 1: create a java project as shown below, add a class "ZipCodeValidator.java", and add a JUnit test class "ZipCodeValidatorTest.java".
Step 2: write the following code in the ZipCodeValidator.java class
Step 3: write the following code in the ZipCodeValidatorTest.java class
Step 4: run the test as JUnit test and see the result in the console and JUnit console. Two zip codes are valid and other two zip codes are not correct, so two tests failed in the assertion.
Result on the console:
Zip Code 12345-6789 true
Zip Code 12345-4567 true
Zip Code 12345-67890 false
Zip Code 12345-abcd false
JUnit Result
Regular Expression Pattern: \b[0-9]{5}(?:-[0-9]{4})?\b
Explanation: (explanation syntax is from http://regex101.com)
Here is the Java source code to validate the US Zip Code regular expression
Step 1: create a java project as shown below, add a class "ZipCodeValidator.java", and add a JUnit test class "ZipCodeValidatorTest.java".
Step 2: write the following code in the ZipCodeValidator.java class
package com.seleniummaster.regularexpression; |
package com.seleniummaster.regularexpression; |
Result on the console:
Zip Code 12345-6789 true
Zip Code 12345-4567 true
Zip Code 12345-67890 false
Zip Code 12345-abcd false
JUnit Result