0

I'm currently working on a project in which I need to fetch street/city details from a DB using a zipcode. Dutch zipcodes use a "1111 AA" format, I would like to have this entered in a single input field while forcing the first four characters to be numeric and the last two to be alphabetical.

I've been googling this quite a bit, have found ways to force either one, but none to combine it into a single input field and I don't seem to be crafty enough to combine them myself.

Thank you.

4 Answers4

1

We use this in alot of sites, especially for phone #s

http://digitalbush.com/projects/masked-input-plugin/

j_mcnally
  • 6,928
  • 2
  • 31
  • 46
0

This is finally a question where regular expressions are a suitable solution.

Try this:

var zip = "1111 AA"
var regex = new RegExp("^[0-9]{4}\\s?[A-Z]{2}$");
regex.test(zip);

Note that this will not allow lowercase characters, and will allow the zipcode without whitespace (like this: 1111AA). Try some googling to find out how to allow or disallow those.

Tim Lamballais
  • 1,056
  • 5
  • 10
  • Aye, you should use that. Google RegEx if you don't know how to use it. – ShouravBR Oct 04 '12 at 17:23
  • the whitespace thing really isn't a problem, I already made it forgiving so either 1111 XX could be entered of 1111XX. `$zipCode = $_GET["q"]; $count = substr_count($zipCode, ' '); if ($count == '0') { $zip = str_split($zipCode, 4); $zipCode = $zip[0].' '.$zip[1]; }` But I don't just want to check the value to be the right format, I wasnt to physically disable them from using alphabetical characters for the first four and numerical for the the last two. – Kevin Consen Oct 05 '12 at 16:00
0

To handle the specific pattern you entered, try something like this in the javascript function that validates form input:

var pattern = new RexExp( '[0-9]{4} [A-Z]{2}' );
if( inputFieldValue.search( pattern ) == -1 )
{
    // throw error condition.
}
else
{
    // The pattern matched. Continue on.
}
Thomas
  • 1,402
  • 1
  • 11
  • 14
0

You can use the new html5 pattern attribute for that:

<form>
   <input name="zipcode" type="text" pattern="\d{4}\s?[A-Z]{2}" length="7" />      
   <input type="submit" />
</form>​​​​​​​​​​​​​​​​​​​​​​​​

If the attribute isn't supported, you fall back to a javascript solution, checking the input field with a regex before submit like the following:

var pattern = /[0-9]{4}\s?[A-Z]{2}/;
string.match(pattern);

Take a look at the demo fiddle.

Christoph
  • 50,121
  • 21
  • 99
  • 128