Albert Asadov
Albert Asadov

Reputation: 3

textfield text (one or more than one) regex check Swift UIKit

I created the regex logic, it works correctly, but in addition to one textfield I can have several of them, I created a dictionary and a variable so that it gives me a bool value of true, provided that all the textfields that pass regex validation were true, but despite this when one textfield returns true allFieldsValid also returns true, I need all textfields to pass the regex check and receive the value true, how can I fix this? and if my code is not correct please help me correct it.

i write my cells cod down

var regexValidate: Bool? = false
var validationResults: [String: Bool] = [:]
var allFieldsValid: Bool? = false
var requiredFields: Set<String> = []


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

  if let regexPattern = regex {
            print("IT IS REGEX!!--> [ \(regexPattern)")
            let prospectiveText = (textField.text as NSString?)?.replacingCharacters(in: range,
             with: string) ?? string
            regexValidate = regexValidate(prospectiveText, withPattern: regexPattern)
            if regexPattern == ""{
                regexValidate = true
            }
            validationResults[paymentParametrName ?? ""] = regexValidate ?? false
            requiredFields.insert(paymentParametrName ?? "")
            allFieldsValid = checkAllFieldsValid()
            print(" IS VALIDATE FOR CURRENT TEXTFIELD?? -->\(regexValidate) ] ---")
            print("--->FULL Validation TEXTFIELDS: \(allFieldsValid)")
        }
   return true
 }


 private func regexValidate(_ text: String, withPattern pattern: String) -> Bool {
    let regex = try? NSRegularExpression(pattern: pattern)
    let range = NSRange(location: 0, length: text.utf16.count)
    let matches = regex?.matches(in: text, options: [], range: range) ?? []
    return matches.count == 1 && matches.first?.range == range
 }

 private func checkAllFieldsValid() -> Bool {
       for field in requiredFields {
           if validationResults[field] != true {
               return false
           }
       }
       return !requiredFields.isEmpty
   }

Upvotes: 0

Views: 57

Answers (1)

Milan Sanghani
Milan Sanghani

Reputation: 16

import UIKit

class ViewController: UIViewController {

    let textField1 = UITextField()
    let textField2 = UITextField()

    override func viewDidLoad() {
        super.viewDidLoad()
        setupTextFields()
    }

    func setupTextFields() {
        textField1.placeholder = "Enter text 1"
        textField2.placeholder = "Enter text 2"

        textField1.borderStyle = .roundedRect
        textField2.borderStyle = .roundedRect

        textField1.translatesAutoresizingMaskIntoConstraints = false
        textField2.translatesAutoresizingMaskIntoConstraints = false

        view.addSubview(textField1)
        view.addSubview(textField2)

        NSLayoutConstraint.activate([
            textField1.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            textField1.centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: -20),
            textField1.widthAnchor.constraint(equalToConstant: 200),

            textField2.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            textField2.topAnchor.constraint(equalTo: textField1.bottomAnchor, constant: 20),
            textField2.widthAnchor.constraint(equalToConstant: 200)
        ])

        textField1.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged)
        textField2.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged)
    }

    func isValidText(_ text: String, pattern: String) -> Bool {
        let regex = try! NSRegularExpression(pattern: pattern)
        let range = NSRange(location: 0, length: text.utf16.count)
        return regex.firstMatch(in: text, options: [], range: range) != nil
    }

    @objc func textFieldDidChange(_ textField: UITextField) {
        let pattern = "^[a-zA-Z0-9]*$" // Example pattern: Alphanumeric characters only
        if let text = textField.text, isValidText(text, pattern: pattern) {
            textField.layer.borderColor = UIColor.green.cgColor
            textField.layer.borderWidth = 1.0
        } else {
            textField.layer.borderColor = UIColor.red.cgColor
            textField.layer.borderWidth = 1.0
        }
    }
}

Upvotes: 0

Related Questions