Skip to content
Advertisement

Validate Postal Code?

I’m doing some tutorials online…and I’m stuck at an exercise:Define a function postalValidate(S) which first checks if S represents a postal code which is valid. Note: I’m supposed to solve it with strings, lists, if statements, loops, and other basic constructs like variables and functions.

first, delete all spaces; the remainder must be of the form L#L#L# where L are letters (in either lower or upper case) and # are numbers.

If S is not a valid postal code, return the boolean False. If S is valid, return a version of the same postal code in the nice format L#L#L# where each L is capital.

I’ve created a code for these exercise, but the grader said that is wrong, however I will post it too.

JavaScript

Advertisement

Answer

This is clearly a job for regular expressions, although I don’t know if you’re supposed to use them in the exercise…

I’m posting this as an answer just in case you can. Otherwise, let us know…

JavaScript

Edit:

Since you can not use regular expressions, I’d recommend you change the way of thinking… Instead of checking if the characters belong to a valid postal code, I’d recommend you do the opposite: check if they DON’T belong in a valid postal code, returning False as soon as you detect a misplaced (or wrong) character:

JavaScript

The return statement stops the execution of the current function so as soon as you realize that there’s something “wrong” with the string to check, you can return False (there’s no point on keeping checking once you know it’s not valid, right?)

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement