简体   繁体   中英

How to check if text in a UITextField matches a specific pattern?

I have a UITextField and I need to check, as the user types, if the text they have entered in the textfield so far matches a specific pattern.

More specifically, I need the text to match the pattern ####-##-## where # is any digit 0-9 and - is a dash (note that this is NOT a phone number or email). For example, the entry 1990-12-09 matches, 1990:12:09 does not match and 1990-12 DOES match because it has not yet violated the pattern (even though the text does not yet completely match the pattern).

How should I approach this? Ideally I would not have to hard code in a series of if statements .

The difficulty is that I want to check if the text in the textfield matches this pattern, as the user types . I don't want to just check it at the end.

I'm thinking that regular expressions are probably the way, but I'm not experienced enough at them to know if they hold the solution.

You could set the keyboard type to myTextField.keyboardType = UIKeyboardTypeNumberPad that why you are limiting the type of input.

Then this post should help answer your formatting question: UITextField format in xx-xx-xxx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM