1
0

More than 3 years have passed since last update.

AndroidとiOSでテキストフィールドの入力文字を制限する

Posted at

やること

  • Android/iOSそれぞれで、テキストフィールドに半角文字のみ入力できるように実装する。

Android

RegexInputFilter.kt
open class RegexInputFilter(private val pattern: String) : InputFilter {
    override fun filter(
        source: CharSequence,
        start: Int,
        end: Int,
        dest: Spanned,
        dstart: Int,
        dend: Int
    ): CharSequence {
        return if (source.toString().matches(Regex(pattern))) {
            source
        } else {
            ""
        }
    }
}

class AlphanumericInputFilter : RegexInputFilter("^[a-zA-Z0-9]+$")

EditTextのfiltersに、半角英数のInputFilterをセットします。

SampleFragment.kt
edit_password.filters = arrayOf(AlphanumericInputFilter())

iOS

UITextFieldのEditing Changedイベントで、不正な文字を削除します。

SampleViewController.swift
@IBAction func textFieldDidChange(_ sender: UITextField) {
    sender.text = (sender.text ?? "").filter({ String($0).isMatch("^[a-zA-Z0-9]+$") })
}

❌ダメだった方法

以下のように UITextFieldDelegate の shouldChangeCharactersInで制限する方法だと、日本語入力された場合に対応できませんでした。

Bad.swift
// ❌ 日本語入力に対応できない
extension SampleViewController: UITextFieldDelegate {
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        let pattern = "^[a-zA-Z0-9]+$"
        return string.isEmpty || string.range(of: pattern, options: .regularExpression, range: nil, locale: nil) != nil
    }
}

参考: UITextFieldで入力された文字の判定や、文字数、Byte数を取得する

1
0
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
1
0