Allow only Numbers for UITextField input - ios

The iPad does not have a "Numpad" keyboard like the iPhone/iPod does.
I'm looking to find how I can restrict the user's keyboard to only accept values 0 through 9.
I would imagine using UITextField's "shouldChangeCharactersInRange" but I don't know the best way to implement it.

This is how you might handle the problem on a SSN verification field, you can modify the max length and remove the if statement checking for keyboard type if you need to.
There is also logic to suppress the max length alerts when the user is typing as opposed to pasting data.
Within the context of this code, presentAlert()/presentAlert: is just some basic function that presents a UIAlertController (or a legacy UIAlertView) using the message string passed.
Swift 5
// NOTE: This code assumes you have set the UITextField(s)'s delegate property to the
// object that will contain this code, because otherwise it would never be called.
//
// There are also some better stylistic approaches in Swift to avoid all the
// nested statements, but I wanted to keep the styles similar to allow others
// to contrast and compare between the two languages a little easier.
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
// Handle backspace/delete
guard !string.isEmpty else {
// Backspace detected, allow text change, no need to process the text any further
return true
}
// Input Validation
// Prevent invalid character input, if keyboard is numberpad
if textField.keyboardType == .numberPad {
// Check for invalid input characters
if CharacterSet(charactersIn: "0123456789").isSuperset(of: CharacterSet(charactersIn: string)) {
// Present alert so the user knows what went wrong
presentAlert("This field accepts only numeric entries.")
// Invalid characters detected, disallow text change
return false
}
}
// Length Processing
// Need to convert the NSRange to a Swift-appropriate type
if let text = textField.text, let range = Range(range, in: text) {
let proposedText = text.replacingCharacters(in: range, with: string)
// Check proposed text length does not exceed max character count
guard proposedText.count <= maxCharacters else {
// Present alert if pasting text
// easy: pasted data has a length greater than 1; who copy/pastes one character?
if string.count > 1 {
// Pasting text, present alert so the user knows what went wrong
presentAlert("Paste failed: Maximum character count exceeded.")
}
// Character count exceeded, disallow text change
return false
}
// Only enable the OK/submit button if they have entered all numbers for the last four
// of their SSN (prevents early submissions/trips to authentication server, etc)
answerButton.isEnabled = (proposedText.count == 4)
}
// Allow text change
return true
}
Objective-C
// NOTE: This code assumes you have set the UITextField(s)'s delegate property to the
// object that will contain this code, because otherwise it would never be called.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
// Handle backspace/delete
if (!string.length)
{
// Backspace detected, allow text change, no need to process the text any further
return YES;
}
// Input Validation
// Prevent invalid character input, if keyboard is numberpad
if (textField.keyboardType == UIKeyboardTypeNumberPad)
{
if ([string rangeOfCharacterFromSet:[NSCharacterSet decimalDigitCharacterSet].invertedSet].location != NSNotFound)
{
[self presentAlert: #"This field accepts only numeric entries."];
return NO;
}
}
// Length Validation
NSString *proposedText = [textField.text stringByReplacingCharactersInRange:range withString:string];
// Check proposed text length does not exceed max character count
if (proposedText.length > maxCharacters)
{
// Present alert if pasting text
// easy: pasted data has a length greater than 1; who copy/pastes one character?
if (string.length > 1)
{
// Pasting text, present alert so the user knows what went wrong
[self presentAlert: #"Paste failed: Maximum character count exceeded."];
}
// Character count exceeded, disallow text change
return NO;
}
// Only enable the OK/submit button if they have entered all numbers for the last four
// of their SSN (prevents early submissions/trips to authentication server, etc)
self.answerButton.enabled = (proposedText.length == maxCharacters);
// Allow text change
return YES;
}

You can use this code to allow only number in textField.
Before that set delegate for textField
textFieldName.delegate=self;
or
[textFieldName setDelegate:self];
Than use this code to allow only digit to textField
- (BOOL) textField: (UITextField *)theTextField shouldChangeCharactersInRange:(NSRange)range replacementString: (NSString *)string {
//return yes or no after comparing the characters
// allow backspace
if (!string.length)
{
return YES;
}
////for Decimal value start//////This code use use for allowing single decimal value
// if ([theTextField.text rangeOfString:#"."].location == NSNotFound)
// {
// if ([string isEqualToString:#"."]) {
// return YES;
// }
// }
// else
// {
// if ([[theTextField.text substringFromIndex:[theTextField.text rangeOfString:#"."].location] length]>2) // this allow 2 digit after decimal
// {
// return NO;
// }
// }
////for Decimal value End//////This code use use for allowing single decimal value
// allow digit 0 to 9
if ([string intValue])
{
return YES;
}
return NO;
}

Try this to avoid textfield clearing issue
Swift 3.0
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
guard NSCharacterSet(charactersInString: "0123456789").isSupersetOfSet(NSCharacterSet(charactersInString: string)) else {
return false
}
return true
}
Swift 4.0
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard CharacterSet(charactersIn: "0123456789").isSuperset(of: CharacterSet(charactersIn: string)) else {
return false
}
return true
}

Very specific steps for Swift code
You can provide logic that restricts the text field's input in the func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool method by implementing the UITextFieldDelegate protocol.
For the sake of clarity, these steps assume that your storyboard contains a View Controller with a text field object that should only accept digits.
Create a custom class for the view controller that extends UIViewController. Make sure that the scene in your storyboard refers to the custom class by setting the custom class value in Xcode's Identity Inspector.
import UIKit
class YourCustomController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
}
Create an outlet from your scene's text field to your custom View Controller.
class YourCustomController: UIViewController {
#IBOutlet weak var numberField: UITextField!
...
}
Apply the UITextFieldDelegate protocol in your custom view controller.
class YourCustomController: UIViewController, UITextFieldDelegate {
...
}
In your custom view controller's viewDidLoad method, assign your text field's delegate to your custom view controller class.
override func viewDidLoad() {
super.viewDidLoad()
numberField.delegate = self
}
Add the UITextFieldDelegate's func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool method.
As a result of making your custom view controller the numberField's delegate in the previous step, this method will be called each time a user enters a character into the text field. If your method returns true then the character will remain in the text field. If your method returns false then the character will not remain in the text field.
The string parameter is the character being entered by the user. If the string character can be converted to an Int then it is between 0 and 9; otherwise, it is some non-number character.
class YourCustomController: UIViewController, UITextFieldDelegate {
...
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
return Int(string) != nil
}
}
(See below for the full view controller code.)
Example View Controller with digits only text field
import UIKit
class YourCustomController: UIViewController, UITextFieldDelegate {
#IBOutlet weak var numberField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
numberField.delegate = self
}
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
return Int(string) != nil
}
}
Example View Controller with a Decimal text field
If you want to support a decimal number then take advantage of NSNumberFormatter. See the code comments for the differences.
import UIKit
class YourCustomController: UIViewController, UITextFieldDelegate {
#IBOutlet weak var numberField: UITextField!
private var formatter: NSNumberFormatter!
override func viewDidLoad() {
super.viewDidLoad()
numberField.delegate = self
// Initialize the formatter; minimum value is set to zero; style is Decimal.
formatter = NSNumberFormatter()
formatter.numberStyle = NSNumberFormatterStyle.DecimalStyle
formatter.minimum = 0
}
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
// Combine the current text field value and the new string
// character. If it conforms to the formatter's settings then
// it is valid. If it doesn't then nil is returned and the
// string character should not be allowed in the text field.
return formatter.numberFromString("\(textField.text)\(string)") != nil
}
}

- (BOOL) textField: (UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString: (NSString *)string {
NSNumberFormatter * nf = [[NSNumberFormatter alloc] init];
[nf setNumberStyle:NSNumberFormatterNoStyle];
NSString * newString = [NSString stringWithFormat:#"%#%#",textField.text,string];
NSNumber * number = [nf numberFromString:newString];
if (number)
return YES;
else
return NO;
}

I applied this and it works!!
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
// Check for non-numeric characters
NSUInteger lengthOfString = string.length;
for (NSInteger index = 0; index < lengthOfString; index++) {
unichar character = [string characterAtIndex:index];
if (character < 48) return NO; // 48 unichar for 0
if (character > 57) return NO; // 57 unichar for 9
}
// Check total length for restrict user
NSUInteger proposedNewLength = textField.text.length - range.length + string.length;
if (proposedNewLength > 6)
return YES;
return YES;
}

swift 5
//MARK:- UITextFieldDelegate
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let allowedCharacters = "1234567890"
let allowedCharcterSet = CharacterSet(charactersIn: allowedCharacters)
let typedCharcterSet = CharacterSet(charactersIn: string)
return allowedCharcterSet.isSuperset(of: typedCharcterSet)
}
You can now just tap 1234567890 only

NSString* val = [[textField text] stringByReplacingCharactersInRange:range withString:string];
NSCharacterSet *allowedCharacterSet = [NSCharacterSet decimalDigitCharacterSet];
if ([[string componentsSeparatedByCharactersInSet:[allowedCharacterSet invertedSet]] count] > 1 || [val length] > 5) {
return NO;
}

Works fine for me :
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if (([string rangeOfCharacterFromSet:[[NSCharacterSet decimalDigitCharacterSet] invertedSet]].location != NSNotFound) && !(range.length==1 && string.length==0)) {
return NO;
}
return YES;
}

In Swift:
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
return string.isEmpty || Int(string) != nil
}

Keep distinct presentation data from internal representation. There is a simpler way. Let NSNumberFormatter do the job:
NSNumberFormatter* ns = [[NSNumberFormatter alloc] init];
ns.numberStyle = NSNumberFormatterDecimalStyle;
[ns setMaximumFractionDigits:2];
// This is your internal representation of the localized number
double a = [[ns numberFromString:self.textIVA.text] doubleValue]];
[mylabel setText:[NSString stringWithFormat:#"€ %#",
[NSNumberFormatter localizedStringFromNumber:
[NSNumber numberWithDouble:a]
numberStyle:NSNumberFormatterDecimalStyle]]];

If you use my specification pattern then code looks like this
textField.delegate = self
lazy var specification: Specification = {
return RegularExpressionSpecification(pattern: "^(|0|[1-9]\\d{0,6})$")
}()
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
let textFieldString: NSString = textField.text ?? ""
let s = textFieldString.stringByReplacingCharactersInRange(range, withString:string)
return specification.isSatisfiedBy(s)
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
let s = textField.text ?? ""
let isTextValid = specification.isSatisfiedBy(s)
if isTextValid {
textField.resignFirstResponder()
}
return false
}

I have modified #iDev's answer to work for digitals and ".":
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
// Check for non-numeric characters
NSUInteger lengthOfString = string.length;
for (NSInteger index = 0; index < lengthOfString; index++) {
unichar character = [string characterAtIndex:index];
if ((character < 48) && (character != 46)) return NO;
// 48 unichar for 0, and 46 unichar for point
if (character > 57) return NO;
// 57 unichar for 9
}
// Check for total length
NSUInteger proposedNewLength = textField.text.length - range.length + string.length;
if (proposedNewLength > 6)
return YES;
return YES;
}

swift 3
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if textField==yourTextFieldOutlet {
if(CharacterSet.decimalDigits.isSuperset(of: CharacterSet(charactersIn: yourTextFieldOutlet.text!))){
//if numbers only, then your code here
}
else{
showAlert(title: "Error",message: "Enter Number only",type: "failure")
}
}
return true
}

Use this code:
NSString* val = [[textField text] stringByReplacingCharactersInRange:range withString:string];
NSCharacterSet *allowedCharacterSet = [NSCharacterSet decimalDigitCharacterSet];
if ([[string componentsSeparatedByCharactersInSet:[allowedCharacterSet invertedSet]] count] > 1 || [val length] > 5) {
return NO;
}

Related

I want to avoid String and special characters in textflied. only use numeric key in my project [duplicate]

The iPad does not have a "Numpad" keyboard like the iPhone/iPod does.
I'm looking to find how I can restrict the user's keyboard to only accept values 0 through 9.
I would imagine using UITextField's "shouldChangeCharactersInRange" but I don't know the best way to implement it.
This is how you might handle the problem on a SSN verification field, you can modify the max length and remove the if statement checking for keyboard type if you need to.
There is also logic to suppress the max length alerts when the user is typing as opposed to pasting data.
Within the context of this code, presentAlert()/presentAlert: is just some basic function that presents a UIAlertController (or a legacy UIAlertView) using the message string passed.
Swift 5
// NOTE: This code assumes you have set the UITextField(s)'s delegate property to the
// object that will contain this code, because otherwise it would never be called.
//
// There are also some better stylistic approaches in Swift to avoid all the
// nested statements, but I wanted to keep the styles similar to allow others
// to contrast and compare between the two languages a little easier.
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
// Handle backspace/delete
guard !string.isEmpty else {
// Backspace detected, allow text change, no need to process the text any further
return true
}
// Input Validation
// Prevent invalid character input, if keyboard is numberpad
if textField.keyboardType == .numberPad {
// Check for invalid input characters
if CharacterSet(charactersIn: "0123456789").isSuperset(of: CharacterSet(charactersIn: string)) {
// Present alert so the user knows what went wrong
presentAlert("This field accepts only numeric entries.")
// Invalid characters detected, disallow text change
return false
}
}
// Length Processing
// Need to convert the NSRange to a Swift-appropriate type
if let text = textField.text, let range = Range(range, in: text) {
let proposedText = text.replacingCharacters(in: range, with: string)
// Check proposed text length does not exceed max character count
guard proposedText.count <= maxCharacters else {
// Present alert if pasting text
// easy: pasted data has a length greater than 1; who copy/pastes one character?
if string.count > 1 {
// Pasting text, present alert so the user knows what went wrong
presentAlert("Paste failed: Maximum character count exceeded.")
}
// Character count exceeded, disallow text change
return false
}
// Only enable the OK/submit button if they have entered all numbers for the last four
// of their SSN (prevents early submissions/trips to authentication server, etc)
answerButton.isEnabled = (proposedText.count == 4)
}
// Allow text change
return true
}
Objective-C
// NOTE: This code assumes you have set the UITextField(s)'s delegate property to the
// object that will contain this code, because otherwise it would never be called.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
// Handle backspace/delete
if (!string.length)
{
// Backspace detected, allow text change, no need to process the text any further
return YES;
}
// Input Validation
// Prevent invalid character input, if keyboard is numberpad
if (textField.keyboardType == UIKeyboardTypeNumberPad)
{
if ([string rangeOfCharacterFromSet:[NSCharacterSet decimalDigitCharacterSet].invertedSet].location != NSNotFound)
{
[self presentAlert: #"This field accepts only numeric entries."];
return NO;
}
}
// Length Validation
NSString *proposedText = [textField.text stringByReplacingCharactersInRange:range withString:string];
// Check proposed text length does not exceed max character count
if (proposedText.length > maxCharacters)
{
// Present alert if pasting text
// easy: pasted data has a length greater than 1; who copy/pastes one character?
if (string.length > 1)
{
// Pasting text, present alert so the user knows what went wrong
[self presentAlert: #"Paste failed: Maximum character count exceeded."];
}
// Character count exceeded, disallow text change
return NO;
}
// Only enable the OK/submit button if they have entered all numbers for the last four
// of their SSN (prevents early submissions/trips to authentication server, etc)
self.answerButton.enabled = (proposedText.length == maxCharacters);
// Allow text change
return YES;
}
You can use this code to allow only number in textField.
Before that set delegate for textField
textFieldName.delegate=self;
or
[textFieldName setDelegate:self];
Than use this code to allow only digit to textField
- (BOOL) textField: (UITextField *)theTextField shouldChangeCharactersInRange:(NSRange)range replacementString: (NSString *)string {
//return yes or no after comparing the characters
// allow backspace
if (!string.length)
{
return YES;
}
////for Decimal value start//////This code use use for allowing single decimal value
// if ([theTextField.text rangeOfString:#"."].location == NSNotFound)
// {
// if ([string isEqualToString:#"."]) {
// return YES;
// }
// }
// else
// {
// if ([[theTextField.text substringFromIndex:[theTextField.text rangeOfString:#"."].location] length]>2) // this allow 2 digit after decimal
// {
// return NO;
// }
// }
////for Decimal value End//////This code use use for allowing single decimal value
// allow digit 0 to 9
if ([string intValue])
{
return YES;
}
return NO;
}
Try this to avoid textfield clearing issue
Swift 3.0
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
guard NSCharacterSet(charactersInString: "0123456789").isSupersetOfSet(NSCharacterSet(charactersInString: string)) else {
return false
}
return true
}
Swift 4.0
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard CharacterSet(charactersIn: "0123456789").isSuperset(of: CharacterSet(charactersIn: string)) else {
return false
}
return true
}
Very specific steps for Swift code
You can provide logic that restricts the text field's input in the func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool method by implementing the UITextFieldDelegate protocol.
For the sake of clarity, these steps assume that your storyboard contains a View Controller with a text field object that should only accept digits.
Create a custom class for the view controller that extends UIViewController. Make sure that the scene in your storyboard refers to the custom class by setting the custom class value in Xcode's Identity Inspector.
import UIKit
class YourCustomController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
}
Create an outlet from your scene's text field to your custom View Controller.
class YourCustomController: UIViewController {
#IBOutlet weak var numberField: UITextField!
...
}
Apply the UITextFieldDelegate protocol in your custom view controller.
class YourCustomController: UIViewController, UITextFieldDelegate {
...
}
In your custom view controller's viewDidLoad method, assign your text field's delegate to your custom view controller class.
override func viewDidLoad() {
super.viewDidLoad()
numberField.delegate = self
}
Add the UITextFieldDelegate's func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool method.
As a result of making your custom view controller the numberField's delegate in the previous step, this method will be called each time a user enters a character into the text field. If your method returns true then the character will remain in the text field. If your method returns false then the character will not remain in the text field.
The string parameter is the character being entered by the user. If the string character can be converted to an Int then it is between 0 and 9; otherwise, it is some non-number character.
class YourCustomController: UIViewController, UITextFieldDelegate {
...
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
return Int(string) != nil
}
}
(See below for the full view controller code.)
Example View Controller with digits only text field
import UIKit
class YourCustomController: UIViewController, UITextFieldDelegate {
#IBOutlet weak var numberField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
numberField.delegate = self
}
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
return Int(string) != nil
}
}
Example View Controller with a Decimal text field
If you want to support a decimal number then take advantage of NSNumberFormatter. See the code comments for the differences.
import UIKit
class YourCustomController: UIViewController, UITextFieldDelegate {
#IBOutlet weak var numberField: UITextField!
private var formatter: NSNumberFormatter!
override func viewDidLoad() {
super.viewDidLoad()
numberField.delegate = self
// Initialize the formatter; minimum value is set to zero; style is Decimal.
formatter = NSNumberFormatter()
formatter.numberStyle = NSNumberFormatterStyle.DecimalStyle
formatter.minimum = 0
}
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
// Combine the current text field value and the new string
// character. If it conforms to the formatter's settings then
// it is valid. If it doesn't then nil is returned and the
// string character should not be allowed in the text field.
return formatter.numberFromString("\(textField.text)\(string)") != nil
}
}
- (BOOL) textField: (UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString: (NSString *)string {
NSNumberFormatter * nf = [[NSNumberFormatter alloc] init];
[nf setNumberStyle:NSNumberFormatterNoStyle];
NSString * newString = [NSString stringWithFormat:#"%#%#",textField.text,string];
NSNumber * number = [nf numberFromString:newString];
if (number)
return YES;
else
return NO;
}
I applied this and it works!!
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
// Check for non-numeric characters
NSUInteger lengthOfString = string.length;
for (NSInteger index = 0; index < lengthOfString; index++) {
unichar character = [string characterAtIndex:index];
if (character < 48) return NO; // 48 unichar for 0
if (character > 57) return NO; // 57 unichar for 9
}
// Check total length for restrict user
NSUInteger proposedNewLength = textField.text.length - range.length + string.length;
if (proposedNewLength > 6)
return YES;
return YES;
}
swift 5
//MARK:- UITextFieldDelegate
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let allowedCharacters = "1234567890"
let allowedCharcterSet = CharacterSet(charactersIn: allowedCharacters)
let typedCharcterSet = CharacterSet(charactersIn: string)
return allowedCharcterSet.isSuperset(of: typedCharcterSet)
}
You can now just tap 1234567890 only
NSString* val = [[textField text] stringByReplacingCharactersInRange:range withString:string];
NSCharacterSet *allowedCharacterSet = [NSCharacterSet decimalDigitCharacterSet];
if ([[string componentsSeparatedByCharactersInSet:[allowedCharacterSet invertedSet]] count] > 1 || [val length] > 5) {
return NO;
}
Works fine for me :
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if (([string rangeOfCharacterFromSet:[[NSCharacterSet decimalDigitCharacterSet] invertedSet]].location != NSNotFound) && !(range.length==1 && string.length==0)) {
return NO;
}
return YES;
}
In Swift:
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
return string.isEmpty || Int(string) != nil
}
Keep distinct presentation data from internal representation. There is a simpler way. Let NSNumberFormatter do the job:
NSNumberFormatter* ns = [[NSNumberFormatter alloc] init];
ns.numberStyle = NSNumberFormatterDecimalStyle;
[ns setMaximumFractionDigits:2];
// This is your internal representation of the localized number
double a = [[ns numberFromString:self.textIVA.text] doubleValue]];
[mylabel setText:[NSString stringWithFormat:#"€ %#",
[NSNumberFormatter localizedStringFromNumber:
[NSNumber numberWithDouble:a]
numberStyle:NSNumberFormatterDecimalStyle]]];
If you use my specification pattern then code looks like this
textField.delegate = self
lazy var specification: Specification = {
return RegularExpressionSpecification(pattern: "^(|0|[1-9]\\d{0,6})$")
}()
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
let textFieldString: NSString = textField.text ?? ""
let s = textFieldString.stringByReplacingCharactersInRange(range, withString:string)
return specification.isSatisfiedBy(s)
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
let s = textField.text ?? ""
let isTextValid = specification.isSatisfiedBy(s)
if isTextValid {
textField.resignFirstResponder()
}
return false
}
I have modified #iDev's answer to work for digitals and ".":
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
// Check for non-numeric characters
NSUInteger lengthOfString = string.length;
for (NSInteger index = 0; index < lengthOfString; index++) {
unichar character = [string characterAtIndex:index];
if ((character < 48) && (character != 46)) return NO;
// 48 unichar for 0, and 46 unichar for point
if (character > 57) return NO;
// 57 unichar for 9
}
// Check for total length
NSUInteger proposedNewLength = textField.text.length - range.length + string.length;
if (proposedNewLength > 6)
return YES;
return YES;
}
swift 3
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if textField==yourTextFieldOutlet {
if(CharacterSet.decimalDigits.isSuperset(of: CharacterSet(charactersIn: yourTextFieldOutlet.text!))){
//if numbers only, then your code here
}
else{
showAlert(title: "Error",message: "Enter Number only",type: "failure")
}
}
return true
}
Use this code:
NSString* val = [[textField text] stringByReplacingCharactersInRange:range withString:string];
NSCharacterSet *allowedCharacterSet = [NSCharacterSet decimalDigitCharacterSet];
if ([[string componentsSeparatedByCharactersInSet:[allowedCharacterSet invertedSet]] count] > 1 || [val length] > 5) {
return NO;
}

Limiting UITextfield length limits all my UITextfields

I have a UITextField that I want to limit the lenght to 4 characters here's the code for it :
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
guard let text = acRegTextField.text else { return true }
let newLength = text.utf16.count + string.utf16.count - range.length
return newLength <= 4 // Bool
}
problem is, with this code, my other text box gets stopped when acRegTextField as 4 char in it.
I honestly don't get it... any help would be appreciated
thanks
If you have numerous textfields on your view and assign the delegate to them then shouldChangeCharactersInRange will apply to all the textfields. So what you can do is if you already have an outlet to the textfield that should contain just 4 characters - then just compare this textfield is the one you want to validate - note the === compares the reference. eg:
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
if acRegTextField === textField {
guard let text = acRegTextField.text else { return true }
let newLength = text.utf16.count + string.utf16.count - range.length
return newLength <= 4 // Bool
}
return true
}
This is a method from UITextFieldDelegate. To make this work, you must have said somewhere
myTextField.delegate = myClass
Every text field you say that for will get the same delegate. If you don't want the limit to apply to a particular textField, then don't set the delegate for that textField.

How to allow only certain set of numbers in a UITextfield in swift 2.0

I am having a UITextField in which i get the month number as input. I am successful in limiting the no of characters to 2 in the UITextField. But i want users to enter only the values from 1 to 12 and none other than that. This has to be done simultaneously when the user types the numbers i.e in func textField(textField: UITextField!, shouldChangeCharactersInRange range: NSRange, replacementString string: String!) -> Bool. If i use a simple if condition to check the each character and return false in else part the textfield won't allow me to use clear or retype any other character. someone help me.
Set keyboard type as Number Pad
add this
func textField(textField: UITextField!, shouldChangeCharactersInRange range: NSRange, replacementString string: String!) -> Bool {
if let text = textField.text {
let newStr = (text as NSString)
.stringByReplacingCharactersInRange(range, withString: string)
if newStr.isEmpty {
return true
}
let intvalue = Int(newStr)
return (intvalue >= 0 && intvalue <= 12)
}
return true
}
You can do it simultaneously by checking the TextField value inside shouldChangeCharactersInRange.
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
let inputStr = textField.text?.stringByAppendingString(string)
let inputInt = Int(inputStr!)
if inputInt > 0 && inputInt < 13 {
return true
} else {
return false
}
}
=> you can Define limite of char like this:-
#define NUMBERS_ONLY #"1234567890"
#define CHARACTER_LIMIT 2
=> and based on define limit char you can use and try it below method :-
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSUInteger newLength = [textField.text length] + [string length] - range.length;
NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:NUMBERS_ONLY] invertedSet];
NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:#""];
return (([string isEqualToString:filtered])&&(newLength <= CHARACTER_LIMIT));
}
func textField(textField: UITextField,
shouldChangeCharactersInRange range: NSRange,
replacementString string: String) -> Bool {
// Create an `NSCharacterSet` set which includes everything *but* the digits
let inverseSet = NSCharacterSet(charactersInString:"0123456789").invertedSet
// At every character in this "inverseSet" contained in the string,
// split the string up into components which exclude the characters
// in this inverse set
let components = string.componentsSeparatedByCharactersInSet(inverseSet)
// Rejoin these components
let filtered = components.joinWithSeparator("") // use join("", components) if you are using Swift 1.2
// If the original string is equal to the filtered string, i.e. if no
// inverse characters were present to be eliminated, the input is valid
// and the statement returns true; else it returns false
return string == filtered
}
see this link-- Limit UITextField input to numbers in Swift
Check out this to set Limit the numbers and allow only numbers 0 to 9.
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if textField == mobileNumber {
let aSet = NSCharacterSet(charactersIn:"0123456789").inverted
let compSepByCharInSet = string.components(separatedBy: aSet)
let numberFiltered = compSepByCharInSet.joined(separator: "")
let length = (mobileNumber.text?.count)! + string.count - range.length
return string == numberFiltered && length <= LIMIT
}else if textField == userType {
return false
}
return true
}
I just want to post a more simplified answer based on the previous answers.
Tested on Swift 5.1
Considering that you already set textField.keyboardType = .numberPad, then you can do the following:
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard let text = textField.text else {
return true
}
let newStr = (text as NSString).replacingCharacters(in: range, with: string)
guard let intValue = Int(newStr) else {
return true
}
return intValue <= maxNumber // maxNumber: replace with your max number
}
You dont´need to validate that intValue is greater or equal to 0 because in numberPad you can NOT write negative values.

Limit UITextField input to numbers in Swift

How can I get limit the user's TextField input to numbers in Swift?
You can use UITextFieldDelegate’s shouldChangeCharactersInRange method to limit the user's input to numbers:
func textField(textField: UITextField,
shouldChangeCharactersInRange range: NSRange,
replacementString string: String) -> Bool {
// Create an `NSCharacterSet` set which includes everything *but* the digits
let inverseSet = NSCharacterSet(charactersInString:"0123456789").invertedSet
// At every character in this "inverseSet" contained in the string,
// split the string up into components which exclude the characters
// in this inverse set
let components = string.componentsSeparatedByCharactersInSet(inverseSet)
// Rejoin these components
let filtered = components.joinWithSeparator("") // use join("", components) if you are using Swift 1.2
// If the original string is equal to the filtered string, i.e. if no
// inverse characters were present to be eliminated, the input is valid
// and the statement returns true; else it returns false
return string == filtered
}
Updated for Swift 3:
func textField(_ textField: UITextField,
shouldChangeCharactersIn range: NSRange,
replacementString string: String) -> Bool {
// Create an `NSCharacterSet` set which includes everything *but* the digits
let inverseSet = NSCharacterSet(charactersIn:"0123456789").inverted
// At every character in this "inverseSet" contained in the string,
// split the string up into components which exclude the characters
// in this inverse set
let components = string.components(separatedBy: inverseSet)
// Rejoin these components
let filtered = components.joined(separator: "") // use join("", components) if you are using Swift 1.2
// If the original string is equal to the filtered string, i.e. if no
// inverse characters were present to be eliminated, the input is valid
// and the statement returns true; else it returns false
return string == filtered
}
For anyone looking for a shorter answer, I've found this quite useful.
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
// remove non-numerics and compare with original string
return string == string.filter("0123456789".contains)
}
Works in XCode 10.1, Swift 4.2
In swift 4.1 and Xcode 10
Add UITextFieldDelegate to your class
class YourViewController: UIViewController, UITextFieldDelegate
Then write this code in your viewDidLoad()
yourTF.delegate = self
Write this textfield delegate function
//MARK - UITextField Delegates
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
//For numers
if textField == yourTF {
let allowedCharacters = CharacterSet(charactersIn:"0123456789")//Here change this characters based on your requirement
let characterSet = CharacterSet(charactersIn: string)
return allowedCharacters.isSuperset(of: characterSet)
}
return true
}
1st you have to inherit the UITextViewDelegate class with you own
class
class ViewController: UIViewController, UITextViewDelegate {
2nd add an IBOutlet
#IBOutlet weak var firstName: UITextField!
3rd you have to assure this object is using
override func viewDidLoad() {
super.viewDidLoad()
firstName.delegate = self
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if textField == firstName {
let allowedCharacters = "1234567890"
let allowedCharacterSet = CharacterSet(charactersIn: allowedCharacters)
let typedCharacterSet = CharacterSet(charactersIn: string)
let alphabet = allowedCharacterSet.isSuperset(of: typedCharacterSet)
let Range = range.length + range.location > (fnameTF.text?.count)!
if Range == false && alphabet == false {
return false
}
let NewLength = (fnameTF.text?.count)! + string.count - range.length
return NewLength <= 10
} else {
return false
}
}
Well the iOS provides no such functionality where you can specify textfield to accept only numeric characters. The only way through would be, one of UITextFieldDelegate methods, which is as follows,
(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
You need to implement the following method and intercept the entered character and either through the following regular expression
"^([0-9]+)?(\\.([0-9]{1,2})?)?$"
or
[NSCharacterSet decimalDigitCharacterSet]
you can find out whether the entered character is numeric and return YES if it matches the regular expression or character set else return NO.

How can I limit the number of decimal points in a UITextField?

I have a UITextField that when clicked brings up a number pad with a decimal point in the bottom left. I am trying to limit the field so that a user can only place 1 decimal mark
e.g.
2.5 OK
2..5 NOT OK
Implement the shouldChangeCharactersInRange method like this:
// Only allow one decimal point
// Example assumes ARC - Implement proper memory management if not using.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
NSArray *arrayOfString = [newString componentsSeparatedByString:#"."];
if ([arrayOfString count] > 2 )
return NO;
return YES;
}
This creates an array of strings split by the decimal point, so if there is more than one decimal point we will have at least 3 elements in the array.
Here is an example with a regular expression, the example limits to only one decimal point and 2 decimals. You can tweak it to fit your needs.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
NSString *expression = #"^[0-9]*((\\.|,)[0-9]{0,2})?$";
NSError *error = nil;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:expression options:NSRegularExpressionCaseInsensitive error:&error];
NSUInteger numberOfMatches = [regex numberOfMatchesInString:newString options:0 range:NSMakeRange(0, [newString length])];
return numberOfMatches != 0;
}
Swift 3 Implement this UITextFieldDelegate method to prevent user from typing an invalid number:
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let text = (textField.text ?? "") as NSString
let newText = text.replacingCharacters(in: range, with: string)
if let regex = try? NSRegularExpression(pattern: "^[0-9]*((\\.|,)[0-9]*)?$", options: .caseInsensitive) {
return regex.numberOfMatches(in: newText, options: .reportProgress, range: NSRange(location: 0, length: (newText as NSString).length)) > 0
}
return false
}
It is working with both comma or dot as decimal separator. You can also limit number of fraction digits using this pattern: "^[0-9]*((\\.|,)[0-9]{0,2})?$" (in this case 2).
Swift 4
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
// Allow to remove character (Backspace)
if string == "" {
return true
}
// Block multiple dot
if (textField.text?.contains("."))! && string == "." {
return false
}
// Check here decimal places
if (textField.text?.contains("."))! {
let limitDecimalPlace = 2
let decimalPlace = textField.text?.components(separatedBy: ".").last
if (decimalPlace?.count)! < limitDecimalPlace {
return true
}
else {
return false
}
}
return true
}
Objective-C
//Create this variable in .h file or .m file
float _numberOfDecimal;
//assign value in viewDidLoad method
numberOfDecimal = 2;
#pragma mark - TextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
// Allow to remove character (Backspace)
if ([string isEqualToString:#""]) {
return true;
}
// Block multiple dot
if ([textField.text containsString:#"."] && [string isEqualToString:#"."]) {
return false;
}
// Check here decimal places
if ([textField.text containsString:#"."]) {
NSString *strDecimalPlace = [[textField.text componentsSeparatedByString:#"."] lastObject];
if (strDecimalPlace.length < _numberOfDecimal) {
return true;
}
else {
return false;
}
}
return true;
}
For Swift 2.3 to prevent user for enter decimal number after two places -
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool
{
let decimalPlacesLimit = 2
let rangeDot = txtPrice.text!.rangeOfString(".", options: .CaseInsensitiveSearch)
if rangeDot?.count > 0
{
if (string == ".")
{
print("textField already contains a separator")
return false
}
else {
var explodedString = txtPrice.text!.componentsSeparatedByString(".")
let decimalPart = explodedString[1]
if decimalPart.characters.count >= decimalPlacesLimit && !(string == "")
{
print("textField already contains \(decimalPlacesLimit) decimal places")
return false
}
}
}
}
Building on the accepted answer, the following approach validates three cases that are helpful when dealing with money formats:
Extremely large amounts
More than 2 characters after the decimal point
More than 1 decimal points
Make sure your text field's delegate is set properly, your class conforms to the UITextField protocol, and add the following delegate method.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
// Check for deletion of the $ sign
if (range.location == 0 && [textField.text hasPrefix:#"$"])
return NO;
NSString *updatedText = [textField.text stringByReplacingCharactersInRange:range withString:string];
NSArray *stringsArray = [updatedText componentsSeparatedByString:#"."];
// Check for an absurdly large amount
if (stringsArray.count > 0)
{
NSString *dollarAmount = stringsArray[0];
if (dollarAmount.length > 6)
return NO;
}
// Check for more than 2 chars after the decimal point
if (stringsArray.count > 1)
{
NSString *centAmount = stringsArray[1];
if (centAmount.length > 2)
return NO;
}
// Check for a second decimal point
if (stringsArray.count > 2)
return NO;
return YES;
}
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if(textField == min_textfield )
{
if([textField.text rangeOfString:#"."].location == NSNotFound)
{
if([string isEqualToString:#"."] )
{
flag_for_text = 1;
}
else
{
textField.text = [NSMutableString stringWithFormat:#"%#",textField.text];
}
}
else
{
if([string isEqualToString:#"."])
{
return NO;
}
else
{
textField.text = [NSMutableString stringWithFormat:#"%#",textField.text];
}
}
}
}
Try this :-
public func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
if(text == "," || text == "." ){
let countdots = textView.text!.componentsSeparatedByString(".").count - 1
if countdots > 0 && (text == "." || text == "," )
{
return false
}
}
return true
}
Swift 3
No need to create an array and check count. Limit user can only place 1 decimal mark like this.
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if (textField.text?.contains("."))! && string.contains(".")
{
return false
}
else
{
return true
}
}
Swift 4
max number of Integers Numbers is 4 i.e., 9999, and max decimal digits limit is 2. So, max number can be 9999.99
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
// 100 is the tag value of our textfield
/*or you may use "if textfield == myTextField{" if you have an IBOutlet to that textfield */
if textField.tag == 100 {
//max length limit of text is 8
if textField.text!.count > 8 && string != "" {
return false
}
let maxLength = 8
let currentString: NSString = textField.text! as NSString
// Use following code If you are inputting price to that text field and want $ to get inserted automatically at start when user starts typing in that textfield or you may put some other character at start instead of $. Otherwise comment the following 3 lines of if condition code
if currentString.length == 0 {
priceTextField.text = "$"
}
//new string after inserting the new entered characters
let newString: NSString =
currentString.replacingCharacters(in: range, with: string) as NSString
if newString.length > maxLength{
return false
}
if (textField.text!.range(of: ".") != nil) {
let numStr = newString.components(separatedBy: ".")
if numStr.count>1{
let decStr = numStr[1]
if decStr.length > 2{
return false
}
}
}
var priceStr: String = newString as String
if (textField.text!.range(of: "$") != nil) {
priceStr = priceStr.replacingOccurrences(of: "$", with: "")
}
let price: Double = Double(priceStr) ?? 0
if price > 9999.99{
return false
}
switch string {
case "0","1","2","3","4","5","6","7","8","9":
return true
case ".":
let array = Array(textField.text!)
var decimalCount = 0
for character in array {
if character == "." {
decimalCount = decimalCount + 1
}
}
if decimalCount == 1 {
return false
} else {
return true
}
default:
let array = Array(string)
if array.count == 0 {
return true
}
return false
}
}
return true
}
SWIFT 5
Improvement
Info : do not allow :
separator at the beginning
zero plus another digit at the start except when you add a separator after
1: set the keyboard type to : Decimal Pad
2: copy past
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
//!\ set the keyboard type to : Decimal Pad /!\\
// CUSTOM SETUP
let c = NSLocale.current.decimalSeparator ?? "."
let limitBeforeSeparator = 2
let limitAfterSeparator = 2
// ---------
var validatorUserInput:Bool = false
let text = (textField.text ?? "") as NSString
let newText = text.replacingCharacters(in: range, with: string)
// Validator
let pattern = "(?!0[0-9])\\d*(?!\\\(c))^[0-9]{0,\(limitBeforeSeparator)}((\\\(c))[0-9]{0,\(limitAfterSeparator)})?$"
if let regex = try? NSRegularExpression(pattern: pattern, options: .caseInsensitive) {
validatorUserInput = regex.numberOfMatches(in: newText, options: .reportProgress, range: NSRange(location: 0, length: (newText as NSString).length)) > 0
}
if validatorUserInput {
// setting data or something eles before the return
if let char = string.cString(using: String.Encoding.utf8) {
let isBackSpace = strcmp(char, "\\b")
if (isBackSpace == -92 && textField.text?.count == 1) {
print("Backspace was pressed")
print(newText)
// do something...
} else {
print("Number Added")
print(newText)
// do something...
}
}
return validatorUserInput
} else {
return validatorUserInput
}
}
3: set in the method, if you want x maximum number of digits before and after the separator
let limitBeforeSeparator = 2
let limitAfterSeparator = 2
In whatever object you set your UITextField's delegate to, add a method that answers to "[- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string]".
Then you can either use a NSNumberFormatter object or you can brute force check for an already existing decimal place mark (returning NO if a decimal mark already exists).
Short told, the number format is as follows [NSString stringWithFormat:#"%9.5f", x]; Where 5 is the decimal after ",".
I made the solution, that brings you control over decimal places count, so user can type only one decimal separator and you can also have a control over decimal places count.
Just set the decimalPlacesLimit value properly.
See the method:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSLog(#"text on the way: %#", string);
NSUInteger decimalPlacesLimit = 2;
NSRange rangeDot = [textField.text rangeOfString:#"." options:NSCaseInsensitiveSearch];
NSRange rangeComma = [textField.text rangeOfString:#"," options:NSCaseInsensitiveSearch];
if (rangeDot.length > 0 || rangeComma.length > 0){
if([string isEqualToString:#"."]) {
NSLog(#"textField already contains a separator");
return NO;
} else {
NSArray *explodedString = [textField.text componentsSeparatedByString:#"."];
NSString *decimalPart = explodedString[1];
if (decimalPart.length >= decimalPlacesLimit && ![string isEqualToString:#""]) {
NSLog(#"textField already contains %d decimal places", decimalPlacesLimit);
return NO;
}
}
}
return YES;
}
Swift 4
The efficient and easy way to avoid multiple decimal points (. or ,) in UITextField:
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if(string == "," || string == "." ){
if ((textField.text?.contains(","))! || (textField.text?.contains("."))!){
return false
}
}
return true
}
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if([string isEqualToString:#"."]) {
BOOL containsDecimal = [textField.text containsString:#"."];
return !containsDecimal;
}
return YES;
}
If textfield text already contains a '.' then return NO else return YES.
Thanks everyone, I needed to limit the number before and after the dot. It was only with a regular expression that this became possible for me.
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if string == "," {
textField.text = textField.text! + "."
return false
}
guard let newTextField = textField.text else { return false }
if !string.isEmpty {
let text = newTextField as NSString
let newText = text.replacingCharacters(in: range, with: string)
if let regex = try? NSRegularExpression(pattern: "^[0-9]{0,4}$*((\\.|,)[0-9]{0,4})?$", options: .caseInsensitive) {
return regex.numberOfMatches(in: newText, options: .reportProgress, range: NSRange(location: 0, length: (newText as NSString).length)) > 0
}
return false
}
return true
// #"^[0-9]{0,3}$*((\\.|,)[0-9]{0,2})?$"
}

Resources