I want to mask an input text with the following format: Aa-1234, where the 2 letters are the initials of US states, separated by a hyphen, and the 4 numbers are the 4-digit zip code: how could I do it with javascript?
I want to mask an input text with the following format: Aa-1234, where the 2 letters are the initials of US states, separated by a hyphen, and the 4 numbers are the 4-digit zip code: how could I do it with javascript?
Have you tried this JQuery library?
http://digitalbush.com/projects/masked-input-plugin/
It does exactly what you want. It doesn't validate user input, it formats the
input text
to enter the data with the mask you pass to it.In your case it would be instantiated as follows:
I don't quite understand what you mean by the word mask, but I think your purpose is to validate that the text provided by the user through the input has the format you want, in this case it is something like "us-1234" or "us- 2375" etc To validate that a given string meets the required format, you can use regular expressions.
The regular expression that models the above format is as follows:
The above means that at the beginning of the string there must be the letter u followed by an s and a hyphen and then 4 numbers between 0-9, the end of the string is the $ sign.
In order to use this in your application you need to use it in the following way:
In the
input
you can use the attributepattern
together with a regular expression to ensure that the input has the format you want. The downside is that it's not supported by all browsers yet: it will work for Chrome, Firefox, Opera or IE10+, but it won't work well with Safari.So what you would have to do is find a regular expression that fits what you want. The idea would be something like this:
So you could have a regular expression like this:
^[a-zA-Z]{2}-[0-9]{5}$
which combined with the attributepattern
would look like this:Another option (in case it
pattern
doesn't work) would be to do it with JavaScript, with the same regular expression. When submitting the form, it would be checked with JavaScript if the field meets the format you want and if not, an error message is displayed and it is not sent.In JavaScript it would look like this:
Now, knowing that the number of states is limited (50) and that there are some special cases (territories, foreign code), you could further limit the two letters that are allowed to just the ones that are valid (eg: AL, AK , TX...) and the regular expression could be like this: