我试图限制用户First_Name只允许字母,因此在点击send_button后它应该响应数字或特殊字符的错误。我在这里找到了一些例子,但是因为它们是基于较旧的版本而构建的,所以我有问题要使其工作。到目前为止,如果此文本字段中的第一个元素不是字母,但代码允许这样的内容(名字=" J123g")或者(例如),我已设法读取名字并抛出错误"马克@#$")并且我不希望这种情况发生。
func isOneLetter(in text: String) -> Bool {
do {
let regex = try NSRegularExpression(pattern: "[a-zA-Z]")
let nsString = text as NSString
let results = regex.matches(in: text, range: NSRange(location: 0, length: nsString.length))
let temp = results.map { nsString.substring(with: $0.range)}
return temp.isEmpty
} catch let error {
print("invalid regex: \(error.localizedDescription)")
return false
}
}
@IBAction func Send_Button(_ sender: AnyObject) {
let UserName = First_Name.text
if (isOneLetter(in: UserName!))
{
DisplayMyAlertMessage(userMessage: "First Name must contain only letter and spaces")
}
}
答案 0 :(得分:3)
您的正则表达式模式检查一个字母数字字符,它与两个不需要的示例相匹配。
此正则表达式检查从开头(^
)到结尾($
)的字符串必须有一个或更多(+
)字母数字字符([a-zA-Z]
)。好处是它将空字符串也视为坏字符。
^[a-zA-Z]+$
答案 1 :(得分:2)
另一种方式可能是:
let userInput = ""
let set = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLKMNOPQRSTUVWXYZ")
if userInput.rangeOfCharacter(from: set.inverted) != nil {
print("ERROR: There are numbers included!")
}
答案 2 :(得分:2)
首先,您必须自己继承UITextViewDelegate类 课
class ViewController: UIViewController, UITextViewDelegate {
第二次添加IBOutlet
@IBOutlet weak var firstName: UITextField!
第三个必须确保该对象正在使用
override func viewDidLoad() {
super.viewDidLoad()
firstName.delegate = self
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if textField == firstName {
let allowedCharacters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
let allowedCharacterSet = CharacterSet(charactersIn: allowedCharacters)
let typedCharacterSet = CharacterSet(charactersIn: string)
let alphabet = allowedCharacterSet.isSuperset(of: typedCharacterSet)
return alphabet
}
}
答案 3 :(得分:0)
更新了swift 3:
如果要验证名称并仅允许用户名字母,则在简单的代码行下使用
//函数定义:
func isValidName(_ nameString: String) -> Bool {
var returnValue = true
let mobileRegEx = "[A-Za-z]{3}" // {3} -> at least 3 alphabet are compulsory.
do {
let regex = try NSRegularExpression(pattern: mobileRegEx)
let nsString = nameString as NSString
let results = regex.matches(in: nameString, range: NSRange(location: 0, length: nsString.length))
if results.count == 0
{
returnValue = false
}
} catch let error as NSError {
print("invalid regex: \(error.localizedDescription)")
returnValue = false
}
return returnValue
}
//函数调用:
var firstName = mEnterFirstNameTextField.text!
let isFirstNameValid = isValidName(firstName)
if isFirstNameValid{
// do user logic
}else{
// show error msg: -> "Enter name is not valid, please enter again..."
}