Format textfield for CPF and CNPJ

丶灬走出姿态 提交于 2021-01-29 08:06:19

问题


How should I handle text formatting in iOS? I'm not talking about Currency or Decimal styles. Since iOS doesn't have setFormat(), it's kind of complicated.

Two examples of the format I want: 123.456.789-10 and 123.456.789/1000-00.

My aim is to format a text field as the user types. Like any normal site does when, for example, you type a phone number. It doesn't comes from a model or anything. The user just needs to type the numbers and when necessary I'll insert the ".","/" or "-".


回答1:


You can use regular expressions to do formatting, like this:

NSRegularExpression *fmt = [NSRegularExpression
    regularExpressionWithPattern:@"(.{1,3})(.{1,3})(.{1,3})(.{1,2})"
                         options:0
                           error:NULL];
NSMutableString *str = [NSMutableString stringWithString:@"12345678910"];
[fmt replaceMatchesInString:str
                    options:0
                      range:NSMakeRange(0, str.length)
               withTemplate:@"$1.$2.$3-$4"];

This transforms the string into 123.456.789-10

In order to apply this formatting dynamically as users type, create NSRegularExpression *fmt upfront, store it in your UITextFieldDelegate, and use it in your textField:shouldChangeCharactersInRange:replacementString: method.




回答2:


I created my own method a couple days ago for checking for valid temperature input. It was a bit of a pain as well because I had to check for: -only numbers -only one decimal point -if there was a negative sign it had to be at the front

I ended up using [my string characterAtIndex:index]; and checking each character, since i would have no more than 4 characters.

EDIT:

Here is some pseudo code

for (every char in your string)
    if(the index of the char % 3 == 2) //every third char, 0,2,5...
        the char must be a . or / or -

    else
        the char must be a number


来源:https://stackoverflow.com/questions/11693724/format-textfield-for-cpf-and-cnpj

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!