5
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Swiftで半角英字のValidation(英字ニックネームなど)

Last updated at Posted at 2016-07-03

半角アルファベットのみで入力させたい場合のバリデーション


extension String {
    
    var isAllHalfWidthCharacter: Bool {
        // 半角も全角も1文字でカウント
        let nsStringlen = self.characters.count
        let utf8 = (self as NSString).UTF8String
        // Cのstrlenは全角を2で判定する
        let cStringlen = Int(bitPattern: strlen(utf8))
        if nsStringlen == cStringlen {
            return true
        }
        
        return false
    }
    
    var isValidNickName: Bool {
        if rangeOfCharacterFromSet(.letterCharacterSet(), options: .LiteralSearch, range: nil) == nil { return false }
        if rangeOfCharacterFromSet(.decimalDigitCharacterSet(), options: .LiteralSearch, range: nil) != nil { return false }
        guard self.isAllHalfWidthCharacter else { return false }
        return true
    }
}

#実用例
isValidNickNameでチェック

   if nickname.isValidNickName {
      // Set Data
   } else {
      // Alert
      let alertController = UIAlertController(
                title: "半角英字のみで入力してください",
                message: "",
                preferredStyle: .Alert)
            let otherAction = UIAlertAction(title: "OK", style: .Default) {
                action in
                self.navigationController?.popToViewController(self.navigationController!.viewControllers[0], animated: true)
            }
            
            alertController.addAction(otherAction)
            presentViewController(alertController, animated: true, completion: nil)
   }


NSStringではlengthでカウントできるのに、
String型ではcharacters.countって長い

5
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?