Nilesh Pol Nilesh Pol - 3 months ago 7
iOS Question

Multiple validations for a single UITextField in swift

I want multiple validation for VIN Number UITextField in Swift


  • It should be Capital letters only

  • It can contain 0-9 Numbers

  • No spaces and special characters allowed

  • Total length must be 16 characters


Answer

do like

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString charactersValue: String) -> Bool

{
    if charactersValue.characters.count == 0 {
        return true
    }

    let currentText = textField.text ?? ""
    let prospectiveText = (currentText as NSString).stringByReplacingCharactersInRange(range, withString: charactersValue)

   return prospectiveText.containsOnlyCharactersIn("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ") &&
        prospectiveText.characters.count <=16


}


extension String {
 func containsOnlyCharactersIn(matchCharacters: String) -> Bool {
    let disallowedCharacterSet = NSCharacterSet(charactersInString: matchCharacters).invertedSet
    return self.rangeOfCharacterFromSet(disallowedCharacterSet) == nil
}
}
Comments