I have to validate a textbox having postal code.The postal code can be two formats as possible
xxxxxxxxx or
xxxxx-xxxx.

My question is can I use two javascript regex for validating a textbox?

Recommended Answers

All 2 Replies

You can use the javascript test method. This method can be used to test for a match in a string. It returns true (match) or false (no match).

<input type="text" id="zip" onkeyup="isValid()" /><br/>
<span id="result"></span>


<script>
function isValid(){
   var zip = document.getElementById('zip');
   var result = document.getElementById('result');
   var isValidZip = /(^\d{9}$)|(^\d{5}-\d{4}$)/.test(zip.value);
   if (isValidZip) { 
    result.innerHTML = "Valid";
   } else {
    result.innerHTML = "Not Valid";
  }
}
 </script>

Thank you.

(\d{5}-\d{4})|\d{9}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.