Validating the email address in UITextField
NSString *emailReg = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailReg];
if ([emailTest evaluateWithObject:yourtextFieldName.text] == NO)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"enter the Valid Mail id" message:@"Please Enter Valid Email Address." delegate:nil cancelButtonTitle:@"okay" otherButtonTitles:nil];
[alert show];
}
Swift
var emailReg: String = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"
var emailTest: NSPredicate = NSPredicate(format: "SELF MATCHES %@", emailReg)
if emailTest.evaluateWithObject(yourtextFieldName.text!) == false {
var alert: UIAlertView = UIAlertView(title: "enter the Valid Mail id", message: "Please Enter Valid Email Address.", delegate: nil, cancelButtonTitle: "okay", otherButtonTitles: "")
alert.show()
}
Swift3
let emailReg = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"
let emailTest = NSPredicate(format: "SELF MATCHES %@", emailReg)
if emailTest.evaluate(withObject: yourtextFieldName.text) == false {
UIAlertView(title: "enter the Valid Mail id", message: "Please Enter Valid Email Address.", delegate: nil, cancelButtonTitle: "okay", otherButtonTitles: "").show()
}
There are better ways to validate an email address.
- (BOOL)validateEmailWithString:(NSString*)email
{
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:email];
}