Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I declare that a text field can only contain an integer?

People also ask

How do I allow only the numeric value in a text box?

By default, HTML 5 input field has attribute type=”number” that is used to get input in numeric format. Now forcing input field type=”text” to accept numeric values only by using Javascript or jQuery. You can also set type=”tel” attribute in the input field that will popup numeric keyboard on mobile devices.


Two things:

  1. Specify the keyboard type to only show the numeric keypad. So, set the keyboardType to .numberPad. This, however is not enough to stop the user from entering invalid characters in the text field. For example, the user is still able to paste text or switch keyboards when using an iPad.

  2. Specify the text field's delegate and implement shouldChangeCharactersInRange that will not accept any characters other than the digits 0 though 9:

    class ViewController: UIViewController, UITextFieldDelegate {
    
        @IBOutlet weak var textField: UITextField!
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            // you can set the following two properties for the text field in Interface Builder, if you'd prefer
    
            textField.delegate = self
            textField.keyboardType = .numberPad
        }
    
        func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
            let invalidCharacters = CharacterSet(charactersIn: "0123456789").inverted
            return string.rangeOfCharacter(from: invalidCharacters) == nil
        }
    
        // or, alternatively:
        //
        // func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
        //     return string.range(of: "^\\d*$", options: .regularExpression) != nil
        // }
    
    }
    

For Swift 2 rendition, see previous revision of this answer.


  1. Make your view controller a UITextFieldDelegate by adding UITextFieldDelegate to the class declaration.
  2. Add IBOutlets for your text field and your button.
  3. In viewDidLoad set your button's isEnabled property to false and set self as the textField.delegate.
  4. Implement textField:shouldChangeCharactersInRange:replacementString: method. This method will be called every time your text field is edited. In there, check if the current text field converts to an Int by calling Int(text) and enable/disable your button as desired.

Here is the code:

class ViewController : UIViewController, UITextFieldDelegate {

    @IBOutlet weak var textField: UITextField!
    @IBOutlet weak var button: UIButton!

    override func viewDidLoad() {
        super.viewDidLoad()
        button.isEnabled = false
        textField.delegate = self
        textField.keyboardType = .numberPad
    }

    func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
        // Find out what the text field will be after adding the current edit
        let text = (textField.text as NSString).stringByReplacingCharactersInRange(range, withString: string)

        if Int(text) != nil {
            // Text field converted to an Int
            button.isEnabled = true
        } else {
            // Text field is not an Int
            button.isEnabled = false
        }

        // Return true so the text field will be changed
        return true
    }
}

Swift 4: How about a simple guard and typecasting to Int as below

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

        guard let _ = Int(string) else {
            button.isEnabled = false
            return true
        }
            button.isEnabled = true
            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)
              return alphabet



      }
  }

Each text field has a keyboardType. You could set this to UIKeyboardType.NumbersAndPunctuation to only show numbers and still have the return key present (defensive UI). You could then use NSScanner's scanInt() to check if textField.text is a valid integer.