iOS determines whether the input string is a pure number

Source: Internet
Author: User

It is mainly used to determine whether the content entered into TextField is not a number, such as when a phone number needs to be entered.

The online view of some information, generally through the agreement.

The following are from: http://www.2cto.com/kf/201404/291718.html

Today, there is a text box in the project that requires only the need to enter a number, first set Uitextfield's keyboard in. Xib to numbers Pad, but when used, the keyboard will be cut back to other keyboards and the content cannot be verified. Through the magic of Baidu I know the following methods to solve the problem:

First let. Xib's Viewcontroller implement Uitextfielddelegate and then associate with the control you want to validate.

Then paste the following code into the class.

-(BOOL) TextField: (Uitextfield *) TextField Shouldchangecharactersinrange: (nsrange) range replacementstring: ( NSString *)string {    return[Self ValidateNumber:string];} -(BOOL) ValidateNumber: (nsstring*) Number {BOOL res=YES; Nscharacterset* Tmpset = [Nscharacterset charactersetwithcharactersinstring:@"0123456789"]; inti =0;  while(I <number.length) {nsstring*string= [Number Substringwithrange:nsmakerange (I,1)]; Nsrange Range= [stringRangeofcharacterfromset:tmpset]; if(Range.length = =0) {res=NO;  Break; } I++; }    returnRes;}

There is another way, I haven't tried this way, but I found it and shared it:

1. Define constants for use

#define NUMBERS @ "0123456789"

2. Do the following

-(BOOL) TextField: (uitextfield*) TextField Shouldchangecharactersinrange: (nsrange) range replacementstring: ( nsstring*)string{Nscharacterset*CS; CS=[[Nscharactersetcharactersetwithcharactersinstring:numbers] invertedset]; NSString*filtered = [[stringCOMPONENTSSEPARATEDBYCHARACTERSINSET:CS] Componentsjoinedbystring:@""]; Boolbasictest= [stringisequaltostring:filtered]; if(!basictest) {Uialertview* Alert = [[Uialertviewalloc] Initwithtitle:@"Tips"message:@"Please enter a number"                                                           Delegate: nil Cancelbuttontitle:@"Determine"Otherbuttontitles:nil];            [Alert show];                     Returnno; } Returnyes;}

The following method can determine whether any string is not a pure number

Reference: http://blog.csdn.net/sike2008/article/details/8315202

1 Using regular expressions

Whether it is a pure number

 + (BOOL) Isnumtext: (nsstring *) str{nsstring  * regex = @ "  (/^[0-9]*$/)  "  ; Nspredicate  * pred = [nspredicate predicatewithformat:@ " self MATCHES%@   " , Regex];    BOOL isMatch  = [pred EVALUATEWITHOBJECT:STR];  if   (IsMatch) { return   YES;  else  { return   NO; }}

The specific regular right also need to see the following second system source I recommend the second kind
-(NSString *) Trimming {return[self Stringbytrimmingcharactersinset: [Nscharactersetwhitespacecharacterset]];} //Judging is not a pure number[Nscharacterset Decimaldigitcharacterset]; if([[Textfield.text stringbytrimmingcharactersinset: [Nscharactersetdecimaldigitcharacterset]]trimming].length >0) {DLog (@"not a pure number ."); }Else{DLog (@"Pure numbers! "); }

Talk about your own ways.

I am the last method of reference, write the judgment in a classification, convenient to use the time of the call

Tested for perfect usability

The following is the code in the classification

@implementationnsstring (number)+ (BOOL) Isnumber: (NSString *)string{        //Judging is not a pure number[Nscharacterset Decimaldigitcharacterset]; if([[stringStringbytrimmingcharactersinset: [Nscharacterset Decimaldigitcharacterset]] trimming].length >0) {        returnNO; }Else{NSLog (@"Pure numbers! "); }        returnYES;}-(NSString *) Trimming {return[self stringbytrimmingcharactersinset: [Nscharacterset whitespacecharacterset];}

Then it is in use, import the classification of the header file, the method can be called

For example:

if (! [NSString IsNumber:self.phoneTextField.text]) {        [self showalertwithtittle:@ ' prompt ' andmessage:@ ' phone can only be a pure number " andoktittle:@" know "];    }

Pop-up prompt box because of the use of more, so the simple prompt box to write a separate method

/** * Show Popup box * * @param tittle title * @param message Hint message * @param oktittle OK button title*/- (void) Showalertwithtittle: (NSString *) tittle andmessage: (NSString *) message andoktittle: (NSString *) oktittle{Uialertcontroller*alertcontroller =[Uialertcontroller alertcontrollerwithtitle:tittle message:message Preferredstyle:uialertcontrollerstylealert    ]; //uialertaction *cancelaction = [uialertaction actionwithtitle:canceltittle style:uialertactionstylecancel Handler : ^ (uialertaction * _nonnull action) {//NSLog (@ "Click the Cancel button"); //    }];Uialertaction *okaction = [uialertaction actionwithtitle:oktittle style:uialertactionstyledefault handler:^ ( Uialertaction *_nonnull Action)            {            }]; //[Alertcontroller addaction:cancelaction];[Alertcontroller addaction:okaction];    [Self Presentviewcontroller:alertcontroller animated:yes completion:nil]; }

In fact, later found, written in the various. m files is not very good, because many controllers may have to use this method, interested friends can try to encapsulate this method into a class.

iOS determines whether the input string is a pure number

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.