1

I want to be able to validate a date.

It's valid entry is 4 characters with a mmyy mask.

I want to make sure that the value entered is indeed a date.

Thanks in advance.

butchcowboy
  • 575
  • 1
  • 8
  • 16

3 Answers3

4
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"mmyy"];
NSDate *date = [dateFormatter dateFromString:YOUR_STRING];


If (date) { 
// CORRECT
}
vodkhang
  • 18,639
  • 11
  • 76
  • 110
0

This dateFormatter-thing is inconvinient to me since it accepts to many things as valid date. ok, the day after yesus was born is indeed a valid date ;-) and also dateformatter is removing 1 hour from my datestring because it seems to calculate with utc time or so...thats why i like to check for correct dates with regular expressions:

[textfield.text rangeOfString:@"^(0[1-9]|[1-2][0-9]|3[0-1])(0[1-9]|1[0-2])(19|20)[0-9]{2}" options:NSRegularExpressionSearch].location == NSNotFound

this example is for german date format

0

User NSDateFormatter's -setDateFormat: and -dateFromString: methods. If the string is not in the correct format, you will get nil returned from -dateFromString:.