Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test UITextField text string to only contain alphanumeric characters

Im trying to complete form validation in Swift and cant find a way of testing for only Alphanumeric characters in a UITextField.text.

Ive found NSCharacterSet to help test if at least 1 letter has been entered (so far):

@IBOutlet weak var username: UITextField!
let letters = NSCharacterSet.letterCharacterSet()

//Check username contains a letter
   if (username.text!.rangeOfCharacterFromSet(letters) == nil) {
        getAlert("Error", message: "Username must contain at least 1 letter")
    }

Now i just need a way to validate that only numbers, letters (maybe even underscores and dashes) to be entered. Loads of stuff out there for Obj-C but I need a SWIFT solution please.

Thank you in advance.

like image 599
Chris Avatar asked Jan 02 '16 14:01

Chris


People also ask

What is alphanumeric string example?

Alphanumeric is a description of data that is both letters and numbers. For example, "1a2b3c" is a short string of alphanumeric characters. Alphanumeric is commonly used to help explain the availability of text that can be entered or used in a field, such as an alphanumeric password field.

What is the difference between string and alphanumeric?

An alphanumeric string is a string that contains only alphabets from a-z, A-Z and some numbers from 0-9. Explanation: This string contains all the alphabets from a-z, A-Z, and the number from 0-9. Therefore, it is an alphanumeric string.

Is space allowed in alphanumeric character?

Alphanumeric characters by definition only comprise the letters A to Z and the digits 0 to 9. Spaces and underscores are usually considered punctuation characters, so no, they shouldn't be allowed.


2 Answers

Check if the inversion of your accepted set is present:

if username.text!.rangeOfCharacterFromSet(letters.invertedSet) != nil {
    print("invalid")
}

letters should probably be alphanumericCharacterSet() if you want to include numbers as well.

If you want to accept underscores or more chars, you will probably have to create a character set by your own. But the inversion logic will stay the same.

like image 53
luk2302 Avatar answered Oct 04 '22 19:10

luk2302


Though it's late to answer, but this answer might be useful to someone.

This is simple and worked like a charm for me.

Swift 3:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    /// 1. replacementString is NOT empty means we are entering text or pasting text: perform the logic
    /// 2. replacementString is empty means we are deleting text: return true
    if string.characters.count > 0 {
        var allowedCharacters = CharacterSet.alphanumerics

        /// add characters which we need to be allowed
        allowedCharacters.insert(charactersIn: " -") // "white space & hyphen" 

        let unwantedStr = string.trimmingCharacters(in: allowedCharacters)
        return unwantedStr.characters.count == 0
    }

    return true
}

Note: This will work for pasting strings into the text field as well. Pasted string will not be displayed in text field if it contains any unwanted characters.

like image 28
Rishi Avatar answered Oct 04 '22 17:10

Rishi