How to validate UITextField input in swift

How to validate UITextField input in swift
November 20, 2018 2 Comments iOS Development Pushpendra Kumar



If you are looking for validation in the swift programming language then you are on the right search. Swift language input validation may be a different kind like username, name, phone number, email address and much more, but you do not need to worry about that. Because if you know the procedure of validation then you can do any kind of validation. Here I am going to tell you two different kind of UITextField validation. One will be done on click of the button and another will be done at the time of entering the input into UITextField.

Let’s take an example of Indian Mobile Number validation with digits and it’s length.

1. Way one on button action : If you want to validate the number after click on button then run the following function for the result.

func mobile_number(string : String) -> Bool {
        var is_check : Bool
        let aSet = NSCharacterSet(charactersIn:"0123456789").inverted
        let compSepByCharInSet = string.components(separatedBy: aSet)
        let numberFiltered = compSepByCharInSet.joined(separator: "")
        is_check = string == numberFiltered
        
        if is_check {
            if string.count != 10 {
                is_check = false
            }
        }
        return is_check
    }

if returning is true then number is valid else number is invalid.

2. Now let’s see the another way : If you want to validate the phone number at the time of entering the input then you need to set the delegate to the input field. So write a single line in your viewDidLoad() method.


yourTextField.delegate = self

You have done with the main function now add an extension to your current class and extend UITextFieldDelegate.

extension MyMainClass : UITextFieldDelegate {
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        if textField == yourTextField {
            var is_check : Bool
            let aSet = NSCharacterSet(charactersIn:"0123456789").inverted
            let compSepByCharInSet = string.components(separatedBy: aSet)
            let numberFiltered = compSepByCharInSet.joined(separator: "")
            is_check = string == numberFiltered
            
            if is_check {
                let maxLength = 10
                let currentString: NSString = textField.text! as NSString
                let newString: NSString = currentString.replacingCharacters(in: range, with: string) as NSString
                is_check = newString.length <= maxLength
            }
            return is_check
        }else {
           return true
        }
    }
}

shouldChangeCharactersIn is the abstract function which is called by default on every input, and if it returns true then the input is authorized else not authorized.

Now let’s take an example of REGX validation. Here I am showing you an example of email validation function.

 func validateEmail(email:String) -> Bool {
        let emailFormat = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}" // this is the REGX
        let emailPredicate = NSPredicate(format:"SELF MATCHES %@", emailFormat)
        return emailPredicate.evaluate(with: email)
    }

This function is only for email validation in swift language. In the sam way you can validate different type of REGX (Regular expression).

Wish you good luck 🙂 Happy Coding


Tags
About The Author
Pushpendra Kumar I am passionate about mobile application development and professional developer at Colour Moon Technologies Pvt Ltd (www.thecolourmoon.com). This website I have made so that I can meet with new challenges and can share here.
Leave Comment
  1. 1

    thunderer

    I ɑm not sure where you are getting your info, but good topic.

    I needs to spend ѕome tіme learning more or understanding more.

    Thanks for magnificent information I ԝas looking for thіs info for my miѕsion.

    Reply
  2. 1

    slates

    Ԍreetings! Verу useful advice in this particular article!
    It іs the little changes that will make the biggest changes.
    Many tһanks for shaгing!

    Reply

Leave a reply

Your email address will not be published.