UITextField Should only take values ​​for a number

I have UITexfields, I want it to only accept the number of other warnings that enter a numerical value. I want motionSicknessTextFiled to only accept a number

NSString*dogswithMotionSickness=motionSicknessTextField.text; NSString*valueOne=cereniaTextField.text; NSString*valueTwo=prescriptionTextField.text; NSString*valueThree=otherMeansTextField.text; NSString*valueFour=overtheCounterTextField.text; 
+29
ios objective-c iphone uitextfield xcode
24 '12 at 9:43
source share
14 answers

In any UITextField from which you get these values, you can specify the type of keyboard that you want to see when someone touches a text field.

For example, a numeric keypad.

Liked this screenshot:

numeric only keyboard will appear

This is easy to install when working with XIB and the Interface Builder built into Xcode, but if you want to understand it programmatically, take a look at the Apple UITextInputTraits protocol man page , in particular, the keyboardType property information .

To filter punctuation characters, set the text field delegate and configure the shouldChangeCharactersInRange method:

 - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {  NSCharacterSet *numbersOnly = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"]; NSCharacterSet *characterSetFromTextField = [NSCharacterSet characterSetWithCharactersInString:textField.text];  BOOL stringIsValid = [numbersOnly isSupersetOfSet:characterSetFromTextField];  return stringIsValid; } 
+53
May 24 '12 at 9:45
source share

Goal c

 - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { if (!string.length) return YES; if (textField == self.tmpTextField) { NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string]; NSString *expression = @"^([0-9]+)?(\\.([0-9]{1,2})?)?$"; NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:expression options:NSRegularExpressionCaseInsensitive error:nil]; NSUInteger numberOfMatches = [regex numberOfMatchesInString:newString options:0 range:NSMakeRange(0, [newString length])]; if (numberOfMatches == 0) return NO; } return YES; } 

Swift 3.0

 func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { if !string.characters.count { return true } do { if textField == self.tmpTextField { var newString = textField.text.replacingCharacters(inRange: range, with: string) var expression = "^([0-9]+)?(\\.([0-9]{1,2})?)?$" var regex = try NSRegularExpression(pattern: expression, options: NSRegularExpressionCaseInsensitive) var numberOfMatches = regex.numberOfMatches(inString: newString, options: [], range: NSRange(location: 0, length: newString.characters.count)) if numberOfMatches == 0 { return false } } } catch let error { } return true } 
+25
Mar 14 '14 at 11:22
source share
 [textField setKeyboardType:UIKeyboardTypeNumberPad]; 
+10
May 24 '12 at 9:47 a.m.
source share

I implemented a fragment that has functions for textField:

  • Check the maximum allowed characters.
  • Check the valid decimal number.
  • Check only numerical numbers.

Code is the delegate method of UITextField . Before using this snippet, you must have the following properties:

  • self.maxCharacters
  • self.numeric // Only int characters.
  • self.decimalNumeric // Only numbers and ".", "," (for certain locales, for example, Russian).

the code:

 - (BOOL)textField:(UITextField *) textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { if(self.numeric || self.decimalNumeric) { NSString *fulltext = [textField.text stringByAppendingString:string]; NSString *charactersSetString = @"0123456789"; // For decimal keyboard, allow "dot" and "comma" characters. if(self.decimalNumeric) { charactersSetString = [charactersSetString stringByAppendingString:@".,"]; } NSCharacterSet *numbersOnly = [NSCharacterSet characterSetWithCharactersInString:charactersSetString]; NSCharacterSet *characterSetFromTextField = [NSCharacterSet characterSetWithCharactersInString:fulltext]; // If typed character is out of Set, ignore it. BOOL stringIsValid = [numbersOnly isSupersetOfSet:characterSetFromTextField]; if(!stringIsValid) { return NO; } if(self.decimalNumeric) { NSString *currentText = [textField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]; // Change the "," (appears in other locale keyboards, such as russian) key ot "." currentText = [currentText stringByReplacingOccurrencesOfString:@"," withString:@"."]; // Check the statements of decimal value. if([fulltext isEqualToString:@"."]) { textField.text = @"0."; return NO; } if([fulltext rangeOfString:@".."].location != NSNotFound) { textField.text = [fulltext stringByReplacingOccurrencesOfString:@".." withString:@"."]; return NO; } // If second dot is typed, ignore it. NSArray *dots = [fulltext componentsSeparatedByString:@"."]; if(dots.count > 2) { textField.text = currentText; return NO; } // If first character is zero and second character is > 0, replace first with second. 05 => 5; if(fulltext.length == 2) { if([[fulltext substringToIndex:1] isEqualToString:@"0"] && ![fulltext isEqualToString:@"0."]) { textField.text = [fulltext substringWithRange:NSMakeRange(1, 1)]; return NO; } } } } // Check the max characters typed. NSUInteger oldLength = [textField.text length]; NSUInteger replacementLength = [string length]; NSUInteger rangeLength = range.length; NSUInteger newLength = oldLength - rangeLength + replacementLength; BOOL returnKey = [string rangeOfString: @"\n"].location != NSNotFound; return newLength <= _maxCharacters || returnKey; } 

Demo:

enter image description here

+7
Jun 04 '15 at 12:51 on
source share

Michael Dauterman's modified answer:

 - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { if(string.length > 0) { NSCharacterSet *numbersOnly = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"]; NSCharacterSet *characterSetFromTextField = [NSCharacterSet characterSetWithCharactersInString:string]; BOOL stringIsValid = [numbersOnly isSupersetOfSet:characterSetFromTextField]; return stringIsValid; } return YES; } 
+5
Jul 29 '15 at 3:02
source share

Here is the Swift solution:

A delegate is set in viewDidLoad:

 _yourTextField.delegate = self 
 let _acceptableCharacters = "0123456789." func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { if (string.characters.count == 0) { return true } if (textField == self._yourTextField) { let cs = NSCharacterSet(charactersInString: self._acceptableCharacters) let filtered = string.componentsSeparatedByCharactersInSet(cs).filter { !$0.isEmpty } let str = filtered.joinWithSeparator("") return (string != str) } return true } 
+2
Nov 25 '15 at 9:36
source share

Swift 4

This allows you to enter numbers only, and you can also set a character limit

 func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { let aSet = NSCharacterSet(charactersIn:"0123456789").inverted let compSepByCharInSet = string.components(separatedBy: aSet) let numberFiltered = compSepByCharInSet.joined(separator: "") if string == numberFiltered { let currentText = textField.text ?? "" guard let stringRange = Range(range, in: currentText) else { return false } let updatedText = currentText.replacingCharacters(in: stringRange, with: string) return updatedText.count <= 10 } else { return false } } 
+2
Jan 02 '19 at 10:32
source share

this is a function that checks that a string contains only a numeric value

 +(BOOL) checkforNumeric:(NSString*) str { NSString *strMatchstring=@"\\b([0-9%_.+\\-]+)\\b"; NSPredicate *textpredicate=[NSPredicate predicateWithFormat:@"SELF MATCHES %@", strMatchstring]; if(![textpredicate evaluateWithObject:str]) { //////NSLog(@"Invalid email address found"); UIAlertView *objAlert = [[UIAlertView alloc] initWithTitle:APP_NAME message:@"please enter valid text." delegate:nil cancelButtonTitle:nil otherButtonTitles:@"Close",nil]; [objAlert show]; [objAlert release]; return FALSE; } return TRUE; } 

check it on the submit button.

+1
May 24 '12 at 9:48 a.m.
source share

I just modified Michael's answer and made it a little easier to implement. Just make sure the delegate of your UITextfield configured for itself.

 yourTxtField.delegate = self; 

In addition, copy and paste this code into your main file.

 - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { if (textField == yourTxtField) { NSCharacterSet *numbersOnly = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"]; NSCharacterSet *characterSetFromTextField = [NSCharacterSet characterSetWithCharactersInString:string]; BOOL stringIsValid = [numbersOnly isSupersetOfSet:characterSetFromTextField]; return stringIsValid; }else { return YES; } } 

If you want to allow the use of a space, just put it in the empty space at the end of CharactersInString , as well:

 @"0123456789" -> @"0123456789 " 

Additionally:

If you want to limit the length of the string, just replace the if function as follows:

 if (textField == yourTxtField) { NSUInteger newLength = [textField.text length] + [string length] - range.length; NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:@"1234567890"] invertedSet]; NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""]; return (([string isEqualToString:filtered])&&(newLength <= 10)); } 

In my case, β€œ10” at the end represents the character limit.

Hurrah!:)

0
Sep 04 '15 at 23:13
source share

This answer triggered some error in Swift 3, here is a working answer:

 func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { if string.characters.count == 0 { return true } do { if textField == self.numberTextField { let nString = textField.text as NSString? let newString = nString?.replacingCharacters(in: range, with: string) let expression = "^([0-9]+)?(\\.([0-9]{1,2})?)?$" let regex = try NSRegularExpression(pattern: expression, options: .caseInsensitive) let numberOfMatches = regex.numberOfMatches(in: newString! as String, options: [], range: NSRange(location: 0, length: (newString?.characters.count)!)) if numberOfMatches == 0 { return false } } } catch let error { } return true } 
0
Apr 19 '17 at 14:34 on
source share

Swift 4.2 port of the best answer here @ almas-adlibek

A bunch of configuration variables:

 private let kMaxTextLength = 8 private let kZeroDotted = "0." private let kZero = "0" private let kDoubleDot = ".." private let kDot = "." private let kPeriod = "," 

Now Swift 4 converts part of the code.

  func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { guard let oldText = textField.text, let swiftRange = Range(range, in: oldText) else { return true } let newText = oldText.replacingCharacters(in: swiftRange, with: string) var currentText = textField.text?.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) // Change the "," (appears in other locale keyboards, such as russian) key ot "." currentText = currentText?.replacingOccurrences(of: kPeriod, with: kDot) // Check the statements of decimal value. if (newText == kDot) { textField.text = kZeroDotted; return false } if (newText.range(of: kDoubleDot) != nil) { textField.text = newText.replacingOccurrences(of: kDoubleDot, with: kDot); return false } // If second dot is typed, ignore it. let dots = newText.components(separatedBy: kDot) if(dots.count > 2) { textField.text = currentText; return false } // If first character is zero and second character is > 0, replace first with second. 05 => 5; if(newText.count == 2) { if(newText[0...0] == kZero && newText != kZeroDotted) { textField.text = newText[1...1] return false } } // Check the max characters typed. let oldLength = textField.text?.count ?? 0 let replacementLength = string.count let rangeLength = range.length let newLength = oldLength - rangeLength + replacementLength; let returnKey = string.rangeOfCharacter(from: CharacterSet.newlines) != nil return newLength <= kMaxTextLength || returnKey; } 
0
Oct 17 '18 at
source share

Swift

 class ExampleVC: UIViewController { let numbers = "0123456789"; override func viewDidLoad() { super.viewDidLoad() let textfield = UITextField(frame: CGRectMake(20, 100, 300, 44)) //make some customization, if you want self.view.addSubview(textfield) textfield.delegate = self; } } extension ExampleVC: UITextFieldDelegate { func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { return string.characters.count > 0 ? numbers.contains(string) : true } } 
-one
Nov 17 '16 at 10:23
source share

Here is a working example for swift 4

 public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { // Allow Backspace if string.count == 0 { return true } // Allow Only Valid Decimal Numbers if let textFieldText = textField.text { let finalText = (textFieldText as NSString).replacingCharacters(in: range, with: string) if Double(finalText) != nil { return true } } return false } 
-one
Dec 25 '17 at 12:15
source share

Another option to enter only numeric values ​​in a text field is to select the keyboard type attribute of the corresponding text field. Attaching a screenshot for reference. Number Pad Selection

-one
Mar 26 '18 at 13:05
source share



All Articles