やること
- 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
}
}