Search code examples
iosswiftvalidationnumbers

validate same number exists more than 6 times in UITextFied in Swift


i just want to know how to validate number in Textfield. i have an UiTextField in that i have to enter 16 digit number, while typing i can repeat same number for maximum 6 times when user try to enter more than 6 times the same number means i need to show warning

for Example 1231125641678923 is accepted 2277890652222256 its not accepted see the number 2 is repeated more than 6 times

here my sample code but its not working for me

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

//        var ErrorAlert:UIAlertView!

    if textField == sampleTextField{

        var updatedTextString : NSString = textField.text! as NSString
        updatedTextString = updatedTextString.stringByReplacingCharactersInRange(range, withString: string)

        if textField.text!.containsString(string) {


//                ErrorAlert=UIAlertView.init(title: "Error!", message: "please Enter Valid Policy Number", delegate: nil, cancelButtonTitle: "Ok")
//                ErrorAlert.show()

            NSLog("error")

        }
    }

Solution

  • var number = "1123455324222323"
    
    for digit in 0...9
    {
      if number.componentsSeparatedByString("\(digit)").count > 7
      { print("found more than 6 times : \(digit)") }
    }