【发布时间】:2016-10-23 15:29:00
【问题描述】:
如何限制用户在文本字段中输入电子邮件地址。 问题是,我的警报没有显示,只需注册而不检查电子邮件字段是否有效
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
}
【问题讨论】:
-
我建议您更新 isValidEmail 以将可选字符串作为参数,而不是字符串,如果它为 nil,则返回 false。它可以避免崩溃(你总是在不检查的情况下打开可选值)
-
旁注,因为这实际上不是您问题的一部分,但我建议删除正则表达式。电子邮件地址正则表达式验证过于复杂,您可能无法考虑所有可能性。如果用户输入了无效的电子邮件,那是他们的问题,而不是你的问题。有关更深入的讨论,请参阅此博客文章:davidcel.is/posts/stop-validating-email-addresses-with-regex
标签: ios swift email-validation