Show error icon automatically in UITextField when validation is failed in swift
<p>I want error icon image will be shown automatically within UITextField when one of validation is failed in swift.</p>

<p><strong>Here is normal stage</strong>
<a href="https://i.stack.imgur.com/EMvnp.png" rel="noreferrer"><img src="https://i.stack.imgur.com/EMvnp.png" alt="enter image description here"></a></p>

<p><strong>Here is error stage when validation is failed</strong>
<a href="https://i.stack.imgur.com/kweaW.png" rel="noreferrer"><img src="https://i.stack.imgur.com/kweaW.png" alt="enter image description here"></a></p>

<p>For that UITextField, I've created custom UITextField as follow</p>

<pre><code>class OvalTextField: UITextField {

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)!
        createBorder()
    }

    required override init(frame: CGRect) {
        super.init(frame: frame)
        createBorder()
    }

    func createBorder(){

        let errorImg = UIImageView (frame: CGRectMake(0, 0, 30, 30))
        errorImg.image = UIImage(named: "error")
        errorImg.contentMode = UIViewContentMode.Left

        self.layer.borderWidth = 1.0
        self.layer.borderColor = UIColor(red:0.93, green:0.93, blue:0.93, alpha:1.0).CGColor
        self.layer.cornerRadius = self.frame.size.height / 2
        self.layer.masksToBounds = true

        let gapLabel = UIView (frame: CGRectMake(60, 0, 10, 40))
        self.leftView = gapLabel
        self.leftViewMode = UITextFieldViewMode.Always

        /* Display that one when validation is failed */
        self.rightView = errorImg;
        self.rightViewMode = UITextFieldViewMode.Always
    }
}
</code></pre>

<p>and used that UITextField in ViewController,</p>

<pre><code>@IBOutlet var txtEmail: OvalTextField!
</code></pre>

<p>if that txtEmail is empty or not valid email address, I want to show error icon message.</p>

<p>Please suggest me how to do it. Thanks in advance.</p>