如何限制用户在文本框中输入电子邮件地址。问题是,我的警告没有显示,只是注册而不检查电子邮件字段是否有效。
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
}发布于 2016-06-21 22:12:36
根据您发布的代码,if (isValidEmail(UserEmailTextFiled.text!)) {...意味着如果电子邮件有效,将显示无效的电子邮件警报。您只需使用! if (!isValidEmail(UserEmailTextFiled.text!)) {反转结果即可。
发布于 2017-11-24 12:04:48
public func isValidEmailAddress() -> Bool {
let emailRegex = "^[\\w!#$%&'*+/=?`{|}~^-]+(?:\\.[\\w!#$%&'*+/=?`{|}~^-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,6}$"
return NSPredicate(format: "SELF MATCHES %@", emailRegex).evaluate(with: self)
}这是SWIFT3.0功能和regex。只需复制/粘贴您的助手或扩展名文件,并使用它。
发布于 2017-11-25 04:41:35
Swift 3.0
extension String {
func nsstring () -> NSString {
return (self as NSString)
}
func isValidEmailAddress () -> Bool
{
var returnValue = true
let emailRegEx = "[A-Z0-9a-z.-_]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,3}"
do {
let regex = try NSRegularExpression(pattern: emailRegEx)
let results = regex.matches(in: self.trimmingCharacters(in: .whitespacesAndNewlines), range: NSRange(location: 0, length: self.characters.count))
if results.count == 0
{
returnValue = false
}
}
catch let error as NSError
{
print("invalid regex: \(error.localizedDescription)")
returnValue = false
}
return returnValue
}
}In ViewController
let isValidEmail = yourtextField?.text?.isValidEmailAddress()
if isValidEmail!
{
//Code Here
}
else
{
//Error Code Here
}https://stackoverflow.com/questions/37955320
复制相似问题