How can I validate a postal code, that is, if there is an exact length or something that validates that it is actually a postal code, this either through a regular expression or in another way, but using JavaScript.
How can I validate a postal code, that is, if there is an exact length or something that validates that it is actually a postal code, this either through a regular expression or in another way, but using JavaScript.
If the only thing you want is to validate that the text that is entered corresponds to the format of a postal code, you only need to create a regular expression.
But if what you want is to know if that format string is accepted by your postal code expression, you would have to consume the data from somewhere, searching a bit I found the following api (Mexico postal codes)
https://github.com/Munett/API-Postal-Codes
which you would only have to request through an ajax request and see if that text has an associated place, and the rest would depend on the logic of your application, according to what you want to do
You can use this expression
^\d{4,5}$
to indicate that it is only valid if it is compared against 4 or 5 digits. (Case for Mexico)Since postal codes are usually written without 0 at the beginning on some occasions, for example
4522 = 04522
.But the only way to know if a postal code really exists is to have a database or file with the ones for the country you need and compare them against it.
If you want a pure javascript solution, you could use an array in a json:
And you only need one cycle to find it
Now there is a problem, since this search has a complexity
O(n)
, if the user searches for the cp 99999, he will have to go through the entire list, of many records, so we could opt for a binary searchI understand that perhaps you want to validate that the entered CP exists and is not false or invented, on some occasion I wanted to implement that and it worked for me by downloading the SEPOMEX DB , the bad thing is that they update it often and delete or add new CP, the recommended thing is a regular phrase:
And using the method
.test()
would be something like the following:A more complete function that I created to validate the CP and that to date works perfectly for me is the following: