如何在iOS swift 4中进行名字验证?

问题描述 投票:1回答:3

我有一个名字验证要在swift4中完成,这是在UITextField。问题在于:

  1. 名字应以字母开头,以字母结尾,
  2. 没有尾随和前导空格。
  3. 它们之间可以有空格,可以包含点。
  4. 应该在7到18个字符之间。

目前我在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
}

任何想法如何实现以下条件。现在我禁用空间,只接受字母表。

任何帮助将非常感谢

ios swift uitextfield uitextfielddelegate
3个回答
1
投票

你可以使用这个功能短而干净的方式

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)
}

测试用例

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,

游乐场测试

enter image description here

编辑

试试以下正则表达式:

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

它还将验证所有条件和长度。


1
投票

您可以使用正则表达式来验证您的条件的名字。

我不是正则表达式的专家,但是here you can see an example

^[a-zA-Z](?:[a-zA-Z\.\s][^\n]*)[a-zA-Z]$

这个正则表达式将返回完整的匹配。您可以检查,如果返回的任何匹配字符串有效。

Link以Swift中的使用正则表达式为例。

您可以使用Swift检查的字符串字符数,例如:

if string.count > 7 && string.count < 18 {
    //String valid
}

1
投票

UITextField获取值时,您可以检查以下两个条件:

  1. 名字应以字母开头和结尾
  2. 最后修剪空白。

其余条件可以在shouldChangeCharactersInRange内部完成,如下所示:

let STRING_ACCEPTABLE_CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz. "
    switch textField {
    case firstName:
        print("firstname")
        //Condition for always accepting backcspaces
        if string == "" {
            return true
        }
        //Condition for restricting space at the begining
        else if textField.text?.count == 0 && string == " " {
            return false
        }
        //Condition for restricing user from entering more than 18 letters
        else if (textField.text?.count)! > 17 {
          return false
        }
        //Condition for only accepting the alphabets.
        else {
            let cs = NSCharacterSet(charactersIn: STRING_ACCEPTABLE_CHARACTERS).inverted
            let filtered = string.components(separatedBy: cs).joined(separator: "")
            return (string == filtered)
        }

要检查最小字母数,最后修剪空格,并在按钮的单击或等效内容中以低于条件的字母开头和结尾:

//Trimming whitespaces at the end
let firstname = firstName.text?.trimmingCharacters(in: .whitespaces)

let letters = NSCharacterSet.letters

let prefix = String((firstname?.first)!)
let suffix = String((firstname?.last)!)

//Checking if First Character is letter
if let _ = prefix.rangeOfCharacter(from: letters) {
    print("letters found")
} else {
    print("letters not found")
}

//Checking if Last Character is letter
if let _ = suffix.rangeOfCharacter(from: letters) {
    print("letters found")
} else {
    print("letters not found")
}

希望这可以帮助。

© www.soinside.com 2019 - 2024. All rights reserved.