Validate fields and other objects in #Swift #iOS
Unfortunately we all know that we can’t put everything what we are working in, on a simple blog, I have to understand this since years ago when I worked at some government department. But I can show what I am doing now just for fun and for registry to me in the future.
we were had some problems here, especially when we’d need to try validate a lot of forms that involved things like UITextField, UISegmentedControl, etc. To solve this issue I had to create one class with methods like:
.insert(object, checkType, labelError, errorMessage) // magic goes here.
.showErrors() // print on screen all erros like below
.count() // return the quantity of erros below
.result() // return if all tests are passed or no.
and the code is easily readable:
@IBAction func onActAll(sender: AnyObject)
{
if ruleThis.result() == false {
ruleThis.showErrors()
} else {
print("Do your segueway or something after success.")
}
}
(You set a trigger for validation, here a button to Next Screen)
Then you assign function pointers to the stack os Validations.
override func viewDidLoad() {
super.viewDidLoad()
ruleThis.insert(object: textFieldCPF,
function: checkIfCPFisValid, errorLabel: labelMessageCPF,
errorMessage: "CPF inválido, sua mensagem personalizada aqui.")
ruleThis.insert(object: textFieldPassword,
function: checkIfPasswordIsValid, errorLabel: labelMessagePassword,
errorMessage: "Sua senha não preenche os resquisitos mínimos de segurança, tente novamente")
ruleThis.insert(object: textFieldInputCEP,
function: checkIfCEPisValid, errorLabel: labelMessageCEP,
errorMessage: "Este CEP não é válido")
ruleThis.insert(object: segmentedOption,
function: checkIfIsSelected, errorLabel: labelMessageSegmented,
errorMessage: "Por favor selecione uma das opções.")
}
Then you make a function validation to the object assigned. This coule be simple as
func checkIfTextIsBlank(obj: AnyObject?) -> Bool
{
var result = false
if let object = obj as? UITextField {
if !object.text!.isEmpty { // if is not nil.
result = true
}
}
return result
}
or a little more complex like this (a validation check for social number in Brazil), and the results are below:
For me the results are cool and work! I really enjoy work with Swift. :)