前言:
以註冊登入來說,我們會希望使用者輸入帳號密碼的格式是正確的(英文、數字、電子郵件)
所以在使用 UITextField 時,可以加上正則表示式,來達成目的
正文:
class ViewController:後面加上 UITextFieldDelegat
class ViewController: UIViewController, UITextFieldDelegat {...}
我的做法是,先設定好格式
let regexPW = "^[A-Z][0-9A-Za-z]{3,9}$" //首字母大寫,加上首字至少4個字,最多10個,密碼格式
let regexEM = "^([a-z0-9_\\.-]+)@([\\da-z\\.-]+)\\.([a-z\\.]{2,6})$" //email格式
接著要設定 Textfield 的 delegate ,不然正則表示不會作用
override func viewDidLoad() {
super.viewDidLoad()
Textfield.delegate = self
}
方法寫好後,可以做一個 Button 按下來觸發,這邊我是用 UILabel 配合 改顏色 來提醒格式錯誤
@IBAction func registerclick(_ sender: Any) {
contentcheck()
}
func compare(regex: String,textField: UITextField) -> Int{
let RE = try! NSRegularExpression(pattern: regex, options: .anchorsMatchLines)
let matchs = RE.matches(in: textField.text!, options: .reportProgress, range: NSRange(location: 0, length: textField.text!.count))
return matchs.count
}
func contentcheck() -> Bool {
if compare(regex: regexEM, textField: registeraccounttextfield) == 1 {
registeraccounttextfield.backgroundColor = #colorLiteral(red: 0.9999960065, green: 1, blue: 1, alpha: 1)
} else {
registeraccounttextfield.backgroundColor = #colorLiteral(red: 0.9942680001, green: 0.8618952632, blue: 0.8470022082, alpha: 1)
registeraccounttextfield.text = ""
registeraccountlabel.text = "請輸入email格式!"
return false
}
if compare(regex: regexPW, textField: registerpasswordtextfield) == 1 {
registerpasswordtextfield.backgroundColor = #colorLiteral(red: 0.9999960065, green: 1, blue: 1, alpha: 1)
}else {
registerpasswordtextfield.backgroundColor = #colorLiteral(red: 0.9942680001, green: 0.8618952632, blue: 0.8470022082, alpha: 1)
registerpasswordtextfield.text = ""
registerpasswordlabel.text = "請輸入4~10個字元,第一個字為英文大寫"
return false
}
if compare(regex: regexPW, textField: registerpasswordagaintextfield) == 1 {
registerpasswordagaintextfield.backgroundColor = #colorLiteral(red: 0.9999960065, green: 1, blue: 1, alpha: 1)
}else {
registerpasswordagaintextfield.backgroundColor = #colorLiteral(red: 0.9942680001, green: 0.8618952632, blue: 0.8470022082, alpha: 1)
registerpasswordagaintextfield.text = ""
registerpasswordagainlabel.text = "請輸入正確的密碼!"
return false
}
return true
}