This time, I would like to implement a method of conditional branching depending on whether the characters entered in the TextField are email addresses.
//Email address or not class
class func isValidMailAddress(_ string: String) -> Bool {
let mailAddressRegEx = "[A-Z0-9a-z._+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"
let mailAddressTest = NSPredicate(format:"SELF MATCHES %@", mailAddressRegEx)
let result = mailAddressTest.evaluate(with: string)
return result
}
I will write the code here
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var Label: UILabel!
@IBOutlet weak var TextField: UITextField!
@IBOutlet weak var Button: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
//Email address or not class
class func isValidMailAddress(_ string: String) -> Bool {
let mailAddressRegEx = "[A-Z0-9a-z._+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"
let mailAddressTest = NSPredicate(format:"SELF MATCHES %@", mailAddressRegEx)
let result = mailAddressTest.evaluate(with: string)
return result
}
@IBAction func ButtonTouchUpInside(_ sender: Any) {
//When the email address is correct
if ViewController.isValidMailAddress(self.TextField.text!) {
Label.text = "Correct email address"
//When the email address is incorrect
} else {
Label.text = "Please enter the correct email address"
}
}
}
Recommended Posts