Does anyone know how to validate an e-mail address in Swift? I found this code:
- (BOOL) validEmail:(NSString*) emailString {
if([emailString length]==0){
return NO;
}
NSString *regExPattern = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
NSRegularExpression *regEx = [[NSRegularExpression alloc] initWithPattern:regExPattern options:NSRegularExpressionCaseInsensitive error:nil];
NSUInteger regExMatches = [regEx numberOfMatchesInString:emailString options:0 range:NSMakeRange(0, [emailString length])];
NSLog(@"%i", regExMatches);
if (regExMatches == 0) {
return NO;
} else {
return YES;
}
}
but I can't translate it to Swift.
Editing, updated for Swift 3:
Original answer for Swift 2:
It's working fine.
@JeffersonBe's answer is close, but returns
true
if the string is "something containing someone@something.com a valid email" which is not what we want. The following is an extension on String that works well (and allows testing for valid phoneNumber and other data detectors to boot.Here is an extension in Swift 3
Just use it like this:
In Swift 4.2 and Xcode 10.1
If you want to use SharedClass.
And call function like this....
Or you can have extension for optional text of UITextField:
how to use:
extension:
Best solution with best result for