Home > Software engineering >  Can I validate both a US and a Canadian Zipcode in the same html5 field?
Can I validate both a US and a Canadian Zipcode in the same html5 field?

Time:05-04

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.

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>

CodePudding user response:

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.

  •  Tags:  
  • html
  • Related