Uitextfield Should Accept Number Only Values

Allow only Numbers for UITextField input

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;
}

UITextField Should accept number only values

In whatever UITextField you're getting these values from, you can specify the kind of keyboard you want to appear when somebody touches inside the text field.

E.G. a numeric-only keyboard.

Like this screenshot:

numeric only keyboard will appear

This is easily set when working with the XIB and the Interface Builder built into Xcode, but if you want to understand this programmatically, take a look at Apple's UITextInputTraits protocol reference page, specifically the keyboardType property information.

To filter out punctuations, set the textfield's delegate and set up 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;
}

How to create TextField that only accepts numbers

tl;dr

Checkout John M's solution for a much better way.


One way to do it is that you can set the type of keyboard on the TextField which will limit what people can type on.

TextField("Total number of people", text: $numOfPeople)
.keyboardType(.numberPad)

Apple's documentation can be found here, and you can see a list of all supported keyboard types here.

However, this method is only a first step and is not ideal as the only solution:

  1. iPad doesn't have a numberPad so this method won't work on an iPad.
  2. If the user is using a hardware keyboard then this method won't work.
  3. It does not check what the user has entered. A user could copy/paste a non-numeric value into the TextField.

You should sanitise the data that is entered and make sure that it is purely numeric.

For a solution that does that checkout John M's solution below. He does a great job explaining how to sanitise the data and how it works.

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

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
}

Limit UITextField 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
}


Related Topics



Leave a reply



Submit