views:

394

answers:

2

Hello,

I am an old developer but new to Objective-C and iPhone development. I am looking for the best way to do form validation for values entered. I have been googling for a while and can't find any good code, but might be using the wrong key worrds, etc... I am looking for things like catching for empty string, numeric validation, date validation, etc... where it catches this either while the user is entering data (input mask type) or on the lost focus of the control.

If you can point me to some good resources that would be great!

Thanks!

Simon.

A: 

I don't know particular resources but you could begin usin NSPredicate to validate fields with regular expressions. For example, for mail validation

BOOL result;    

NSString* emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"; 
NSPredicate* emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex]; 

result = [emailTest evaluateWithObject:anEmailAddress];
Espuz
A: 

The emailRegex suggested by Espuz has a slight problem. The range operator "-" within the [] brackets should be escaped otherwise emails having "-" character are returned as invalid.

I am using the following regex string for pattern matching that allows "_", "-" and "." characters in the address:

                    NSString *emailRegex = @"[a-zA-Z0-9.\\-_]{2,32}@[a-zA-Z0-9.\\-_]{2,32}\.[A-Za-z]{2,4}";
                    NSPredicate *regExPredicate =
                        [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
                    BOOL validEmail = [regExPredicate evaluateWithObject:txtField.text];
bhavinb