Postal Code Validation Javascript Example
postal code validation javascript example for production applications
Pattern Views
2,834
↗ 12.5%Last 30 days
Community Rating
⭐
95%
304 likes
Regular Expression
/^\d{5}(-\d{4})?$/
Explanation
This regex pattern validates postal code validation javascript example. Commonly used by developers for input validation and form checking.
Code Examples
JavaScript Example
javascript
// postal code validation javascript example - JavaScript
const regex = /^\d{5}(-\d{4})?$/;
function validate(input) {
if (!input || typeof input !== 'string') return false;
return regex.test(input.trim());
}
// Usage examples
console.log(validate('12345')); // true
console.log(validate('1234')); // falsePython Example
python
# postal code validation javascript example - Python
import re
pattern = r"^\d{5}(-\d{4})?$"
regex = re.compile(pattern)
def validate(input_str):
if not input_str or not isinstance(input_str, str):
return False
return bool(regex.match(input_str.strip()))
# Usage examples
print(validate('12345')) # True
print(validate('1234')) # FalsePHP Example
php
<?php
// postal code validation javascript example - PHP
function validate($input) {
if (!is_string($input) || empty(trim($input))) {
return false;
}
$pattern = '/^\d{5}(-\d{4})?$/';
return preg_match($pattern, trim($input)) === 1;
}
// Usage examples
var_dump(validate('12345')); // bool(true)
var_dump(validate('1234')); // bool(false)
?>Test Cases
✓ Should Match
12345
12345-6789
✗ Should NOT Match
1234
invalid
Performance
Speed
fast
Memory
minimal