UITextField Swift中仅允许使用字母和空格 [英] Only Alphabet and whitespace allowed in UITextField Swift

查看:355
本文介绍了UITextField Swift中仅允许使用字母和空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想验证仅检查字母&的文本字段.允许使用空格,如果指定了数字,则它将返回警告错误.

I want to validate my textField that check only Alphabet & whitespace allowed, If number was given then it will return warning error.

//First I declare my value to variable
var nameValue: String = mainView.nameTextField.text!

//Then I declare this 
 let set = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLKMNOPQRSTUVWXYZ")        

//And this is the validation
if(nameValue.rangeOfCharacter(from: set.inverted) != nil ){
    self.showAlert(message: "Must not contain Number in Name")
   } else {
      //other code
   }


ex: nameValue : "abcd" it works, but 
if nameValue : "ab cd" whitespace included, it returns the showAlert message.

此代码有效,但仅适用于字母,我现在需要的是字母和空格.我声明的是一个硬编码.也许你们在这种情况下有更好的代码和选项.

This code works but only for alphabets, What I need now is alphabets and a whitespace. and what I declare was a hardcode I guess. Maybe you guys have better code and options for this case.

谢谢.

推荐答案

最简单的方法是在字符集中添加新行,例如

The easiest way will be to add new line to the character set like

let set = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLKMNOPQRSTUVWXYZ ")

即在所包含的字符集""

i.e, adding white space character at the end of the included character set" "

除了使用硬编码之外,您还可以使用正则表达式,例如

Rather than hardcoding you can use regular expression like

   do {
    let regex = try NSRegularExpression(pattern: ".*[^A-Za-z ].*", options: [])
    if regex.firstMatch(in: nameValue, options: [], range: NSMakeRange(0, nameValue.characters.count)) != nil {
         self.showAlert(message: "Must not contain Number in Name")

    } else {

    }
}
catch {

}

这篇关于UITextField Swift中仅允许使用字母和空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆