Generic way to validate textField inputs in Swift

iOSApps/ApplicationsMobile Development

How often you develop an application and you write same validation for every input fields. One such example is User registration, Login screen or Registration screen or any other screen. It becomes tedious to write same line of code for every input field moreover you may tend to mistake the same.

As per the design it is never recommend to write validation for each field, rather you should be writing generic validation functions.

So in this blog we will be writing generic validation library of input Text Fields.

Advantages of writing genetic validation library.

  • Reuse able code for all functions.
  • Chances of human error getting reduced.
  • Very fast to setup and hook into your code.
  • Can rewrite one function and will reflect in all.
  • Changing one function will change all.

Let’s get started,

We will be developing our validation library and validation application where, we will be validating 4 inputs fields with our library.

Our library will be generic and completey expanded as per the need.

Step 1 − Open Xcode, Single View Application, name it Validtion.

Step 2 − Create new class, File -→ add new file -→ Swift file -→ Validtion.swift.

Step 3 − Open Main.storyboard and add the UI as show below

We’ve added 4 text field and a button, After entering all the fields when the user taps on validate buttons, it validates all the fields and print which was entered incorrectly, if all goes well it prints all Fields are correct.

Step 4 − Create @IBAction for button and @IBOutlet for all the input fields

import UIKit
class ViewController: UIViewController {
   override func viewDidLoad() {
      super.viewDidLoad()
   }
   @IBOutlet var validateNameTxtFld: UITextField!
   @IBOutlet var validateEmailTxtFld: UITextField!
   @IBOutlet var validatePasswordTxtFld: UITextField!
   @IBOutlet var validatePhoneTxtFld: UITextField!
   @IBAction func validateBtn(_ sender: Any) {
   }
}

Step 5 − Open Validation.swift, here we will be adding our validation code.

Copy the below code and pase in Validation.swift

import Foundation
class Validation {
   public func validateName(name: String) ->Bool {
      // Length be 18 characters max and 3 characters minimum, you can always modify.
      let nameRegex = "^\\w{3,18}$"
      let trimmedString = name.trimmingCharacters(in: .whitespaces)
      let validateName = NSPredicate(format: "SELF MATCHES %@", nameRegex)
      let isValidateName = validateName.evaluate(with: trimmedString)
      return isValidateName
   }
   public func validaPhoneNumber(phoneNumber: String) -> Bool {
      let phoneNumberRegex = "^[6-9]\\d{9}$"
      let trimmedString = phoneNumber.trimmingCharacters(in: .whitespaces)
      let validatePhone = NSPredicate(format: "SELF MATCHES %@", phoneNumberRegex)
      let isValidPhone = validatePhone.evaluate(with: trimmedString)
      return isValidPhone
   }
   public func validateEmailId(emailID: String) -> Bool {
      let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"
      let trimmedString = emailID.trimmingCharacters(in: .whitespaces)
      let validateEmail = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
      let isValidateEmail = validateEmail.evaluate(with: trimmedString)
      return isValidateEmail
   }
   public func validatePassword(password: String) -> Bool {
      //Minimum 8 characters at least 1 Alphabet and 1 Number:
      let passRegEx = "^(?=.*[A-Za-z])(?=.*\\d)[A-Za-z\\d]{8,}$"
      let trimmedString = password.trimmingCharacters(in: .whitespaces)
      let validatePassord = NSPredicate(format:"SELF MATCHES %@", passRegEx)
      let isvalidatePass = validatePassord.evaluate(with: trimmedString)
      return isvalidatePass
   }
   public func validateAnyOtherTextField(otherField: String) -> Bool {
      let otherRegexString = "Your regex String"
      let trimmedString = otherField.trimmingCharacters(in: .whitespaces)
      let validateOtherString = NSPredicate(format: "SELF MATCHES %@", otherRegexString)
      let isValidateOtherString = validateOtherString.evaluate(with: trimmedString)
      return isValidateOtherString
   }
}

We can manipulate the RegexString for each input as per the requirement.

Step 6 − Open ViewController.swift, and create an object of Validation.swift

var validation = Validation()

Now, We will be using guard to unwrap the input fields

guard let name = validateNameTxtFld.text, let email = validateEmailTxtFld.text, let password = validatePasswordTxtFld.text,
   let phone = validatePhoneTxtFld.text else {
   return
}

Step 7 − We will now call our validate functions for each field, and will check if it returns false will return and print “Field invalid”

let isValidateName = self.validation.validateName(name: name)
if (isValidateName == false) {
   print("Incorrect Name")
   return
}
let isValidateEmail = self.validation.validateEmailId(emailID: email)
if (isValidateEmail == false){
   print("Incorrect Email")
   return
}
let isValidatePass = self.validation.validatePassword(password: password)
if (isValidatePass == false) {
   print("Incorrect Pass")
   return
}
let isValidatePhone = self.validation.validaPhoneNumber(phoneNumber: phone)
if (isValidatePhone == false) {
   print("Incorrect Phone")
   return
}

Step 8 − If all fields are correct we will be printing “All fields are correct”

if (isValidateName == true || isValidateEmail == true || isValidatePass == true || isValidatePhone == true) {
   print("All fields are correct")
}

We are done! Checkout final code for VeiwController.swift

import UIKit
class ViewController: UIViewController {
   var validation = Validation()
   override func viewDidLoad() {
      super.viewDidLoad()
   }
   @IBOutlet var validateNameTxtFld: UITextField!
   @IBOutlet var validateEmailTxtFld: UITextField!
   @IBOutlet var validatePasswordTxtFld: UITextField!
   @IBOutlet var validatePhoneTxtFld: UITextField!
   @IBAction func validateBtn(_ sender: Any) {
      guard let name = validateNameTxtFld.text, let email = validateEmailTxtFld.text, let password = validatePasswordTxtFld.text,
      let phone = validatePhoneTxtFld.text else {
         return
      }
      let isValidateName = self.validation.validateName(name: name)
      if (isValidateName == false) {
         print("Incorrect Name")
         return
      }
      let isValidateEmail = self.validation.validateEmailId(emailID: email)
      if (isValidateEmail == false) {
         print("Incorrect Email")
         return
      }
      let isValidatePass = self.validation.validatePassword(password: password)
      if (isValidatePass == false) {
         print("Incorrect Pass")
         return
      }
      let isValidatePhone = self.validation.validaPhoneNumber(phoneNumber: phone)
      if (isValidatePhone == false) {
         print("Incorrect Phone")
         return
      }
      if (isValidateName == true || isValidateEmail == true || isValidatePass == true || isValidatePhone == true) {
         print("All fields are correct")
      }
   }
}
raja
Published on 24-May-2019 12:16:03
Advertisements