1

Possible Duplicate:
Check that an email address is valid on iOS

What is the regex syntax I can use for email validation in iOS for my UITextField.text value? And is there a way for me to check if other UITextField or UITextView is missing?

Can I use this to test for blank values:

if(content.text == nil){
    //do something
}
else{
    //proceed with next course of action
}
Community
  • 1
  • 1
Joe Shamuraq
  • 1,245
  • 3
  • 18
  • 32
  • See http://stackoverflow.com/questions/3139619/check-that-an-email-address-is-valid-on-ios – Rob Jun 17 '12 at 16:40

3 Answers3

2

To be absolutely sure that you have tested for a blank value, you should also test for an empty string.

This construct does it, and leads to less typing than using isEqualToString:, but it is largely a question of personal preference:

if ( content.text == nil || content.text.length == 0 ) {

}

People with a more intimate knowledge of the Objective-C runtime might point out that testing for nil is redundant, as sending a message to nil will always yield nil (or 0), so content.text.length is nil if content.text is. Also, if your surroundings are populated with hard-core C coders, they could similarly point out that testing for 0 in an if statement is for wimps.

Hence, the typing can be reduced to the following, at the cost of some clarity of your code:

if ( !content.text.length ) {

}

As for a regex to test an email address, there is a good discussion here, and the regex in Cocoa can be done like this:

NSPredicate *regexPred = [NSPredicate predicateWithFormat: @"self matches[cd] '<email regex here>'"];
BOOL match = [regexPred evaluateWithObject: content.text];
Monolo
  • 18,205
  • 17
  • 69
  • 103
2

So for the first part (email validation) here is what I would do:

if (content.text == nil //check if its nil (i dont think this is actually possible but who knows
    || content.text.length == 0 //check for the length to have some sort of magnitude
    || [content rangeOfString:@"@"].location == NSNotFound) { //check if its an email they put in
//do your error stuff
}

Now for checking other textfields/textviews you would need to show more code. It is very well possible, however it depends on how you implemented the class. If you have them as ivars you can directly do checks on the ivars, otherwise you could navigate the view hierarchy to find them and then do checks, do you follow?

DanZimm
  • 2,528
  • 2
  • 19
  • 27
-4

Simply set

[textField setKeyboardType:UIKeyboardTypeEmailAddress];

and you'll avoid the pain of trying to do email validation correctly.

Graham
  • 6,484
  • 2
  • 35
  • 39