kvra13 kvra13 - 5 months ago 18
Swift Question

Email validation swift 2

how do I restrict users enter email address into the textfield.
the proplem my alert not show just signup withe out check email if validation or not

if ( username.isEmpty || email.isEmpty || password.isEmpty || phonenumper.isEmpty) {

let alert = UIAlertController(title: "Sign Up Failed!", message:"Please enter your data for Signup", preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "OK ", style: .Default) { _ in })
self.presentViewController(alert, animated: true){}
}

else {
if (isValidEmail(UserEmailTextFiled.text!)) {
let alert = UIAlertController(title: "Inviled Email", message:"Please enter your Email", preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "OK ", style: .Default) { _ in })
self.presentViewController(alert, animated: true){}

}else{
//code

}
func isValidEmail(testStr:String) -> Bool {
let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"
let range = testStr.rangeOfString(emailRegEx, options:.RegularExpressionSearch)
let result = range != nil ? true : false
return result
}

Answer

According to your posted code, if (isValidEmail(UserEmailTextFiled.text!)) {... means that the invalid email alert will be displayed if the email is valid. You just need to reverse the result with a ! if (!isValidEmail(UserEmailTextFiled.text!)) {

Comments