Say you’re building an app where you need to verify the user’s age to be between 18 and 100. An easy way to do this is to have the user input their birthdate with a Date Picker and a little coding.
Setup:
We have a basic view controller with a label, date picker, and a button. The label is static, the date picker will be used to input the birthdate, and the button will be used to validate. The goal is to verify the user’s age and display an alert saying “Valid Age” if it is valid, and vice versa for invalid. Also, remember to set the date picker’s mode to Date.
Now let’s create an outlet for the date picker and an action for the validate button:
Whenever the validate button is pressed, we’ll want to verify the date picker’s date to two dates; the minimum date (18) and the maximum date (100). The current date right now is 2/23/2017, so we could create two hard-coded date constants for 2/23/1999 and 2/23/1917 and ta-da!
But wait, what about tomorrow? We’ll have to update the variables again! And in 30 years? We’ll have to do the same, again! We want something that will work any day we run the program. Instead, let’s create two constants that will always use the current date as the base so we don’t have to keep manually changing things:
To speed things up, let’s set up a check list of things we need to do now:
- Create function that accepts a date parameter and will determine if it is in between the set minimum and maximum ages.
- Call that function whenever the validate button is pressed
- If the date is in between, display an alert saying it is valid, and vice versa if it isn’t.
A few notes:
- If you’re wondering why I’m passing in a date parameter into validateAge(), it’s because this allows you to unit test this because you’re passing in everything it needs; Dependency injection, look it up.
- I also set up a showAlert() method as a wrapper to display alerts in case you want to easily display alerts instead of having to create objects for each message you want to display.
So now let’s test this:
Looks great!
In this case, a user could use ANY date they desired and it would work fine because you already have code to determine if it’s in between 18 and 100. But let’s think for a second about the design. Why don’t we just set the minimum and maximum dates of the date picker, so we’d force them to pick a legitimate date? User friendly right? So let’s just throw this into the viewDidLoad() function. This is the final product:
Mess around with the date picker now. You can move it past the bounds, but it’ll automatically move back.
Hope this helps!