iphone app Form validation
Hi how can I validate email addre开发者_C百科ss, username, fullname and date of birth for my registration form inside an iphone application.
You can use NSPredicate with regular expressions in iPhone OS > 3.0 like so
- (BOOL) validateEmail: (NSString *) candidate {
NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
return [emailTest evaluateWithObject:candidate];
}
Another simple way of validating an email address is using the US2FormValidator framework.
Example:
US2ValidatorEmail *emailValidator = [US2ValidatorEmail alloc] init];
US2ConditionCollection *collection1 = [emailValidator checkConditions:@"example@example.com"];
// collection1 == nil, thus YES
US2ConditionCollection *collection2 = [emailValidator checkConditions:@"example@example."];
// collection2.length > 0, thus NO
US2ConditionCollection *collection3 = [emailValidator checkConditions:@"example"];
// collection3.length > 0, thus NO
BOOL isValid = [emailValidator checkConditions:@"example@example.com"] == nil;
// isValid == YES
You can simply use the US2ValidatorTextField instead of UITextField and connect to this US2ValidatorEmail. The text field will tell you what went wrong and if the user corrected the text.
The framework can be found on GitHub or Softpedia.
If you would like to only check phone numbers iOS also provides so called NSDataDetector's.
Usage like:
theTextView.dataDetectorTypes = UIDataDetectorTypePhoneNumber;
Read more about it here: http://developer.apple.com/library/ios/#documentation/Foundation/Reference/NSDataDetector_Class/Reference/Reference.html
精彩评论