fjcaetano / NSStringMask

NSStringMask allows you to apply masks or formats to NSStrings using NSRegularExpression to input your format.
http://fjcaetano.github.io/NSStringMask/
MIT License
241 stars 36 forks source link

Mask with static number at the beginning #18

Closed fariza-z closed 6 years ago

fariza-z commented 6 years ago

I have an issue with the pattern, I'm trying to create phone number mask with static +7 at the beginning

My mask now looks like this "\\+(\\d{1}) \\((\\d{3})\\) (\\d{3}) (\\d{4})"

what I want is to input static first digit "\\+7 \\((\\d{3})\\) (\\d{3}) (\\d{4})"

However, it inputs 7 before every digit I dial on my numberpad keyboard. How can I solve this problem?

fjcaetano commented 6 years ago

Hi @fariza-z. Do you want the text field to always have the number 7 at the start, or is it 7 the only valid first digit that the user can input?

Also, to clarify the behavior that you're currently experiencing, do you mean that every digit that the user inputs has a 7 in front? For instance, if you type 4 and then 5, does it output 7475? Or does the textfield always start with 7?

fariza-z commented 6 years ago

@fjcaetano I want textfield always have number 7 at the start, and the behavior is like following,

When I type 5 it puts 7 at the beginning resulting in 75 which is right for the first digit, but then when I type next digits what it does is - for example, typing next 4 it goes 7754, then 3 it goes 777543 and etc. At the end, as I continue to type digits on keyboard(and even when I tap backspace to erase), all it does is just put another 7 at the beginning, resulting in all available characters in textfield becoming 7s.

fjcaetano commented 6 years ago

@fariza-z The thing is that you need to specify a capture group which should only have one number 7, so your pattern should actually be this:

\\+(7{1}) \\((\\d{3})\\) (\\d{3}) (\\d{4})

Feel free to reopen the issue if it doesn't solve your situation.

fariza-z commented 6 years ago

@fjcaetano what you are suggesting doesn't quite solve my problem. As I said earlier, I want textfield to always have number 7 at the start. When user starts dialing his numbers, it should appear before entered digits.

In the pattern you are proposing it gets 7 as the only valid first digit user can input. In other words, it does noting when I dial anything but 7, that is not what I'm looking for.

fjcaetano commented 6 years ago

There's no way to do that because you're trying to match two characters, and the user can't input 2 chars at once.

With the solution I gave you, you can always setup the textfield so it starts with +7 by default, but you won't be able to prevent the user from deleting the 7, however, even if they do so, they'll only be able to input 7 as the first digit anyway.