iosswiftuitextfielduitextfielddelegate

How to have a firstname validation in iOS swift4?


I have a first name validation to be done in swift4 which is in a UITextField. The thing is that:

  1. The Firstname should start with a letter and end with a letter,
  2. No trailing and leading whitespace.
  3. It can have spaces between them, can contain dot.
  4. should be between 7 and 18 characters.

Currently i am having the following validation in the UITextField

public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    let STRING_ACCEPTABLE_CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
    switch textField {
    case firstName:
        print("firstname")
        if string == " " {
            return false
        } else {
            let cs = NSCharacterSet(charactersIn: STRING_ACCEPTABLE_CHARACTERS).inverted
            let filtered = string.components(separatedBy: cs).joined(separator: "")
            return (string == filtered)
        }
    }
    return true
}

Any idea how to implement the following conditions. Right now I am disabling the space and only accepts the alphabets.

Any help will be very much appreciated


Solution

  • You can use this func for short and clean way

    func isValid(testStr:String) -> Bool {
        guard testStr.count > 7, testStr.count < 18 else { return false }
    
        let predicateTest = NSPredicate(format: "SELF MATCHES %@", "^(([^ ]?)(^[a-zA-Z].*[a-zA-Z]$)([^ ]?))$")
        return predicateTest.evaluate(with: testStr)
    }
    

    Test cases

    isValid(testStr: " MyNameIsDahiya") // Invalid, leading space
    isValid(testStr: "MyNameIsDahiya ") // Invalid, trailing space
    isValid(testStr: " MyNameIsDahiya ") // Invalid, leading & trailing space
    isValid(testStr: "1MyNameIsDahiya") // Invalid, Leading num
    isValid(testStr: "MyNameIsDahiya1") // Invalid, trailing num
    isValid(testStr: "1MyNameIsDahiya1") // Invalid, leading & trailing num
    isValid(testStr: "MyName") // Invalid, length below 7
    isValid(testStr: "MyNameIsDahiyaBlahhblahh") // Invalid, length above 18
    
    isValid(testStr: "MyNameIsDahiya") // Valid,
    isValid(testStr: "Mr. Dahiya") // Valid,
    

    Playground Test

    enter image description here

    Edit

    Try this below regex:

    (?mi)^[a-z](?!(?:.*\.){2})(?!(?:.* ){2})(?!.*\.[a-z])[a-z. ]{5,16}[a-z]$
    

    It will validate all the conditions and length also.