Skip to content

Instantly share code, notes, and snippets.

@rsaenzi
Created June 15, 2019 05:03
Show Gist options
  • Select an option

  • Save rsaenzi/42a70da750d9148fe12b47016cf2ef8b to your computer and use it in GitHub Desktop.

Select an option

Save rsaenzi/42a70da750d9148fe12b47016cf2ef8b to your computer and use it in GitHub Desktop.
Function that contains common validations for a textfield
//
// CommonTextfieldValidations.swift
//
// Created by Rigoberto Sáenz Imbacuán (https://www.linkedin.com/in/rsaenzi/)
// Copyright © 2019. All rights reserved.
//
extension MyViewController: UITextFieldDelegate {
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
// Deletion is enabled
if string.count == 0 {
return true
}
// Only numbers are permitted
guard string.rangeOfCharacter(from: CharacterSet.decimalDigits.inverted) == nil else {
return false
}
// Max digits allowed
let fullLength: Int = textField.text!.count + string.count
if fullLength > 10 {
return false
}
return true
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment