Reputation: 191
I'm trying to create a email validation that validates where there is character @
in the email and characters before and after @
. I'm able to this but I can't be able to combine both together. So far I have a computed property that just checks if the email contains @
. How can I combine this together to check all conditions.
extension String {
var isEmailFormat: Bool {
if let range = self.range(of: "@") {
_ = self[(self.startIndex)..<range.lowerBound]
_ = self[range.upperBound...]
}
return self.contains("@")
}
}
if !self.emailField.text!.isEmailFormat {
self.addErrorMessage("Invalid email address")
}
Upvotes: 0
Views: 626
Reputation: 1398
//Iam using Custom validator
func validatorEmail(TF1:UITextField,errorMsg:String = validatorConstants.errorMsg ,errorMsgEmail:String = validatorConstants.emailMsg,fieldName:String = "Email" ) -> Bool {
var error = validatorConstants.errorMsg
if fieldName.count > 0 {
error = validatorConstants.customMsg + fieldName
}
if TF1.text?.isEmpty == true{
// Any Notification
return false
}
if TF1.text?.isValidEmail == false{
// Any Notification
return false
}
return true
}
var isValidEmail: Bool {
let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}"
let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
return emailTest.evaluate(with: self)
}
// call this function as
guard validator.validators(TF1: self.txtfied,fieldName: "FirstName") == false
else {
return
}
Upvotes: 0
Reputation: 1113
It's better to use a regular expression in cases like this.
func isValidEmail(testStr:String) -> Bool {
let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"
let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
return emailTest.evaluate(with: testStr)
}
If you want to use 2 booleans, use a return statement like
return condition1 && condition2
but I'm assuming you already know that.
Upvotes: 2
Reputation: 8011
Try this way
var isEmailFormat: Bool {
if let range = self.range(of: "@"),
range.lowerBound > self.startIndex,
range.upperBound < self.endIndex {
return true
} else {
return false
}
}
Logic behind removing the contains logic
If the string itself not containing the @
character, then the range
would be deliberately nil
. So not required in this case.
Upvotes: 1
Reputation: 539745
Additional (boolean) clauses are separated from the optional binding with a comma:
if let range = self.range(of: "@"), condition1, condition2 { ... }
However, assiging a slice to _
does not test anything, it should be something like this:
var isEmailFormat: Bool {
if let range = self.range(of: "@"),
range.lowerBound > startIndex,
range.upperBound < endIndex {
return true
} else {
return false
}
}
Alternatively:
var isEmailFormat: Bool {
if let range = self.range(of: "@") {
return range.lowerBound > startIndex && range.upperBound < endIndex
} else {
return false
}
}
Upvotes: 3