Reputation: 35
I have created a function which shows an error to the right side of the UITextField when for example the email is invalid with bad characters, I want to show the error when the user is live typing it not when the user finish the writing but I can't seem to figure that out also the image doesn't remove itself after the user starts typing again it just stays there.
If anyone has any idea on how I can show the error while the user is typing and how to remove it when it starts typing after the error is shown that would help me and help the future swiftians.
Code:
func setPaddingView(strImgname: String,txtField: UITextField){
let imageView = UIImageView(image: UIImage(named: "cross"))
imageView.frame = CGRect(x: 0, y: 0, width: imageView.image!.size.width , height: imageView.image!.size.height)
let paddingView: UIView = UIView.init(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
paddingView.addSubview(imageView)
txtField.rightViewMode = .always
txtField.rightView = paddingView
}
func textFieldDidEndEditing(_ textField: UITextField)
{
if (textField == firstNameFieldSignUp)
{
let name_reg = "[A-Za-z0-9]{2,20}"
let name_test = NSPredicate(format: "SELF MATCHES %@", name_reg)
if name_test.evaluate(with: firstNameFieldSignUp.text) == false
{
self.setPaddingView(strImgname: "cross", txtField: firstNameFieldSignUp)
}
}
if (textField == lastNameFieldSignUp)
{
let name_reg = "[A-Za-z0-9]{3,20}"
let name_test = NSPredicate(format: "SELF MATCHES %@", name_reg)
if name_test.evaluate(with: lastNameFieldSignUp.text) == false
{
self.setPaddingView(strImgname: "cross", txtField: lastNameFieldSignUp)
}
}
Upvotes: 0
Views: 124
Reputation: 46
@ioslifer textFieldDidEndEditing
is called when the textfiled end editing (resign), adding target to textfield on viewDidload()
may help you for expected result you want
textField.addTarget(self, action: #selector(textDidChange(_:)), for: .valueChanged)
@objc func textDidChange(_ sender: UITextField) {
// validation logic here
}
Upvotes: 2