我想在UItable视图单元格上验证emailId。所以我已经这样做了:
let cell = (tableView.dequeueReusableCellWithIdentifier("QuestionWithEmailField", forIndexPath: indexPath) as? QuestionWithEmailField)!
cell.model = model
cell.indexPath = indexPath
cell.TexitFieldEmail.delegate = self
cell.lblEmail.text = model.labelText
return cell
此单元格用于电子邮件,还有其他单元格用于电话号码和邮政编码。不同类型的字段有不同的单元格。现在我如何验证Emailand使用 DidEndEditingTextField 。
在我的QuestionWithEmailField.swift中,我已经这样做了:
@IBOutlet weak var lblEmail: UILabel!
@IBOutlet weak var TexitFieldEmail: UITextField!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
//email validations functions
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
}
@IBAction func DidEndEditingTextField(sender: AnyObject) {
let validEmailAddress = isValidEmail(TexitFieldEmail.text!)
if validEmailAddress
{
print("Valid Email Address")
}
else{
print("InvalidAddrss")
}
}
但我无法验证此UITextField的电子邮件。现在我想在按下发送按钮后验证该字段。我可以这样做吗?? ??
答案 0 :(得分:0)
您只需要在包含该文本字段的TableviewCell
内进行验证。
您可能会注意到在键盘上按didEndEditing
时将不会调用return
。因此,您必须使用textFieldShouldReturn
中的UITextFieldDelegate
来触发didEndEditing
。
extension String {
var isEmail: Bool {
do {
let regex = try NSRegularExpression(pattern:"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}", options: .caseInsensitive)
return regex.firstMatch(in: self, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: NSMakeRange(0, self.characters.count)) != nil
}
catch {
return false
}
}
}
class TextFieldTableViewCell: UITableViewCell, UITextFieldDelegate {
@IBOutlet weak var textField: UITextField!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
textField.delegate = self
}
@IBAction func didEndEditing(_ sender: UITextField) {
if sender.text!.isEmail {
print("YES")
} else {
print("NO")
}
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
self.endEditing(true)
return false
}
}