How to show runtime validation using SkyFloatingLabelTextField POD in Swift?

  1. add POD pod ‘SkyFloatingLabelTextField’

2. add required textfield and subclass it from SkyFloatingLabelTextField

in viewController.swift add following code

//
//  ViewController.swift
//  Login
//
//  Created by Sandesh on 17/04/20.
//  Copyright © 2020 Sandesh. All rights reserved.
//

import UIKit
import SkyFloatingLabelTextField

class ViewController: UIViewController {
    
    
    @IBOutlet weak var username: SkyFloatingLabelTextField!
    @IBOutlet weak var password: SkyFloatingLabelTextField!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // pass one textfiled in loop and get editchanged event
        [username,password].forEach { (textField) in
             textField.addTarget(self, action: #selector(self.validateField(_:)), for: .editingChanged)
        }

    }
    
    // to validate as per requirment
    func validator() {
        self.setEmptyError()

        if isEmptyOrNil(string: username.text!) {
            username.errorMessage = "Username is empty"
        }else if isEmptyOrNil(string: password.text!) {
             password.errorMessage = "Password is empty"
        }else{
            //do the server auth
            print("valid form submitted")
        }
    }

    //reset errorMessage
    private func setEmptyError(){
        username.errorMessage = ""
        password.errorMessage = ""
    }
    
    
    @IBAction func btnLogin(_ sender: Any) {
        validator()
    }
    
    // required validation methods
    func isEmptyOrNil(string: String?) -> Bool {
        guard let trimmedString = string?.trimmingCharacters(in: NSCharacterSet.whitespaces) else { return false }
        if (trimmedString.isEmpty || string == "") {
            return true
        }
        return false
    }
    
    // on edirchanged validation
    @objc private func validateField(_ textFiled: UITextField) {
        if textFiled == username {
            if isEmptyOrNil(string: username.text!) {
                username.errorMessage = "Username is empty"
            }else{
                username.errorMessage = ""
            }
        }else {
            if isEmptyOrNil(string: password.text!) {
                 password.errorMessage = "Password is empty"
            }else{
                password.errorMessage = ""
            }
        }
    }
}


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s