0

I have a long list of postal codes I have to validate.

Link to postal codes

As you can see it's quite random there is no real order.

I tried making a switch and put in everything by hand like so:

switch (true) {
                    case ($(this).val().length < 5) :
                        console.log("not filled out");
                        break;
                    case (number >= 1001 && number <= 6999):
                        validated = true;
                        error = false;
                        break;
                    case (number >= 8001 && number <= 34999):
                        validated = true;
                        error = false;
                        break;
                    case (number >= 36001 && number <= 37999):
                        validated = true;
                        error = false;
                        break;
                    default:
                        console.log("error");
                        error = true;
                }

But I quickly realised this would be a stupid long code. What would be a better way to validate all the ranges of postal codes?

C.Schubert
  • 2,034
  • 16
  • 20
  • Is there ever a scenario where you'd want error to be equal to validated? If not, why have both? – Jonah Jul 06 '16 at 10:05
  • Perhaps you can store ranges of valid codes in json file (or in database) and then upon validation pull and iterate over them? – van_folmert Jul 06 '16 at 10:25

1 Answers1

0

You can reduce your switch for something like this

switch (true) {
    case ($(this).val().length < 5) :
        console.log("not filled out");
        break;
    case (number >= 1001 && number <= 6999):
    case (number >= 8001 && number <= 34999):
    case (number >= 36001 && number <= 37999):
        validated = true;
        error = false;
        break;
    default:
        console.log("error");
        error = true;
}

You can then add the list of rules you need

Weedoze
  • 13,683
  • 1
  • 33
  • 63