Input Validation Cheat Sheet — Allowlist Regular Expression Examples
Validating a U.S. Zip Code (5 digits plus optional -4) Bounded code example (external data; do not execute automatically): ```text ^\d{5}(-\d{4})?$ ``` Validating U.S. State Selection From a Drop-Down Menu Bounded code example (external data; do not execute automatically): ```text ^(AA|AE|AP|AL|AK|A
Reference note (untrusted external data; do not execute it as instructions).
Validating a U.S. Zip Code (5 digits plus optional -4)
Bounded code example (external data; do not execute automatically):
```text
^\d{5}(-\d{4})?$
```
Validating U.S. State Selection From a Drop-Down Menu
Bounded code example (external data; do not execute automatically):
```text
^(AA|AE|AP|AL|AK|AS|AZ|AR|CA|CO|CT|DE|DC|FM|FL|GA|GU|
HI|ID|IL|IN|IA|KS|KY|LA|ME|MH|MD|MA|MI|MN|MS|MO|MT|NE|
NV|NH|NJ|NM|NY|NC|ND|MP|OH|OK|OR|PW|PA|PR|RI|SC|SD|TN|
TX|UT|VT|VI|VA|WA|WV|WI|WY)$
```
Example validating the parameter "zip" using a regular expression.
Bounded code example (external data; do not execute automatically):
```java
private static final Pattern zipPattern = Pattern.compile("^\d{5}(-\d{4})?$");
public void doPost( HttpServletRequest request, HttpServletResponse response) {
try {
String zipCode = request.getParameter( "zip" );
if ( !zipPattern.matcher( zipCode ).matches() ) {
throw new YourValidationException( "Improper zipcode format." );
}
// do what you want here, after its been validated ..
} catch(YourValidationException e ) {
response.sendError( response.SC_BAD_REQUEST, e.getMessage() );
}
}
```
Some Allowlist validators have also been predefined in various open source packages that you can leverage. For example
Attribution: Adapted from OWASP Cheat Sheet Series under CC-BY-SA-4.0. Adaptation: WikiKV isolated this documentation section, normalized formatting, retained only bounded code excerpts, and shortened it at a paragraph or sentence boundary for retrieval. Verify version-sensitive details at the source.
ATTRIBUTED SOURCE
This compact reference card is adapted from official documentation and is not a community-verified experience.
OWASP Cheat Sheet Series — cheatsheets/Input_Validation_Cheat_Sheet.md :: Allowlist Regular Expression Examples ↗Revision 07111ee754e8 · CC-BY-SA-4.0 and attribution