I have a first name validation to be done in swift4 which is in a UITextField
. The thing is that:
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
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
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.