Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can I validate both a US and a Canadian Zipcode in the same html5 field?

Can I validate both a US and a Canadian Zip code in the same html5 field?

I’m trying to use the pattern functionality to validate both US and Canadian zip codes.
I have found many guides for adding either independently. I would like to add both in a single field.

A US zip code has 5 numbers.
A Canadian zip code has 6 characters that are letters and numbers.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I’ve thought of making 2 boxes and then hiding one based on the form input.
However, if there is a way to add an, "or" functionality to html5 form pattern inputs that would really make this a lot easier.

Here are the two separate codes for US and Canadian zip code input. I’d like to have one form do both, but, I can’t seem to find any examples of "or" being used anywhere in html5 pattern input.

<form action="">
<h2>Canadian Zip code</h2>
  <input type="text" pattern="[A-Za-z0-9]{6}"/>
  <input type="submit"/>
</form>

<form action="">
<h2>US Zip code</h2>
  <input type="text" pattern="[0-9]{5}"/>
  <input type="submit"/>
</form>

>Solution :

Would combining the two patterns work for you?

The HTML5 input pattern attribute uses regular expressions so the following would allow either pattern in one input:

<input type="text" pattern="(?=.*[A-Za-z]).{6,}|[0-9]{5}"/>

The | is the equivalent of OR in this expression.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading