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.
Here is a method based on
rangeOfString
:Note: updated TLD length.
Here is the definitive RegEx for email as per RFC 5322, note that this is best not used because it only checks the basic syntax of email addresses and does not check is the top level domain exists.
See Regular-Expressions.info for more complete information on email RegExs.
Note that no escaping as required by a language such as Objective-C or Swift.
For swift 2.1: this works correctly with email foo@bar
I made a library designed for input validations and one of the "modules" allows you to easily validate a bunch of stuff...
For example to validate an email:
SwiftCop is the library... hope it help!
Seems to work too...
I would suggest using it as an extension of String:
And to use it:
And for Swift 3: