Reputation: 1378
I have a textfield where the user can enter their date of birth, now i wants to make sure whether the input is of date format before saving into database. I gone through the SO , but still i didn't get the answer. Can anyone tell me how to validate(is it date) the input.
The date format would be MM/DD/YYYY
Note:I don't want the user to select date through date picker.
Upvotes: 2
Views: 10551
Reputation: 25692
NSString *dateFromTextfield = @"07/24/2013";
//Extra validation, because the user can enter UTC date as completely in textfield,
//Here i assumed that you would expect only string lenth of 10 for date
//If more than digits then invalid date.
if ([dateFromTextfield length]>10) {
//Show alert invalid date
return;
}
//If you give the correct date format then only date formatter will convert it to NSDate. Otherwise return nil.
//So we can make use of that to find out whether the user has entered date or not.
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"MM/dd/yyyy"];
NSDate *date = [dateFormat dateFromString:dateFromTextfield];
[dateFormat release];
//If date and date object is kind of NSDate class, then it must be a date produced by dateFormat.
if (date!=nil && [date isKindOfClass:[NSDate class]]) {
//User has entered date
// '/' and numbers only entered
}
else{
//Show alert invalid date
//Other than that date format.
}
Upvotes: 1
Reputation: 5545
Try this
NSString *dateFromTextfield = @"07/24/2013";
// Convert string to date object
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"MM/dd/yyyy"];// here set format which you want...
NSDate *date = [dateFormat dateFromString:dateFromTextfield];
[dateFormat release];
and then check
//set int position to 2 and 5 as it contain / for a valid date
unichar ch = [dateFromTextfield characterAtIndex:position];
NSLog(@"%c", ch);
if (ch == '/')
{
//valid date
}
else
{
//not a valid date
}
Upvotes: 4
Reputation: 7637
First of all, use UIDatePicker
because it's designed special for this, it's a natural way to select a date on iOS platform.
Anyway if you want to check if string from UITextField
is a date, format (using a formatter) it and get date relying on formatter
NSString *dateAsString = @"2010-05-24" // string from textfield
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd"];
NSDate * dateFromString = [myDateFormatter dateFromString:dateAsString];
If NSDate
is not nil, then it's ok, else something is wrong: user typed not a date or date which user typed has a wrong format.
TRY TO PROVIDE A HINT FOR USER, LIKE EXAMPLE: 'DATE SHOULD HAVE FORMAT: yyyy-dd-MM'
Upvotes: 1
Reputation: 30
Convert string to date in my iPhone app
Then check if it is or isn't nil. Maybe also check that it is within a reasonable bound for whatever your application is
Upvotes: 1