18
14

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でひらがなとカタカナのバリデーションをする

Last updated at Posted at 2015-12-07

Solution

  • バリデーションライブラリとして、SwiftCopを使用します。
  • HogeTrialという独自のバリデーションクラスを作成し、trialメソッドでひらがなとカタカナのバリデーションを実装します。
import Foundation
import SwiftCop

// SwiftCop[https://github.com/andresinaka/SwiftCop]用のバリデーションクラス
public enum HogeTrial: TrialProtocol {
  case Required
  case Hiragana
  case Katakana
      
  public func trial() -> ((evidence: String) -> Bool){
    switch self {
    case .Hiragana:
      return { (evidence: String) -> Bool in
        // 全て全角ひらがなかどうか
        let hiraganaRegEx = "^[ぁ-ゞ]+$"
        let hiraganaTest = NSPredicate(format:"SELF MATCHES %@", hiraganaRegEx)
        return hiraganaTest.evaluateWithObject(evidence)
      }
    case .Katakana:
      return { (evidence: String) -> Bool in
        // 全て全角カタカナかどうか
        let hiraganaRegEx = "^[ァ-ヾ]+$"
        let hiraganaTest = NSPredicate(format:"SELF MATCHES %@", hiraganaRegEx)
        return hiraganaTest.evaluateWithObject(evidence)
      }
    default:
        return { (evidence: String) -> Bool in
            return false
        }
    }
  }
}

使用方法

class ViewController: UIViewController {
  @IBOutlet weak var nameHiraganaTextField: UITextField!
  @IBOutlet weak var nameKatakanaTextField: UITextField!

  // Let's create a cop!
  let swiftCop = SwiftCop()

  override func viewDidLoad() {
    super.viewDidLoad()

    swiftCop.addSuspect(Suspect(view: nameHiraganaTextField, sentence: "ひらがなを入力してください", trial: HogeTrial.Hiragana))
    swiftCop.addSuspect(Suspect(view: nameKatakanaTextField, sentence: "カタカナを入力してください", trial: HogeTrial.Katakana))
  }
}

参考

18
14
3

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
18
14

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?