mardi 13 mars 2018

What design pattern to make validators for textfield inputs?

I am building the on-boarding for my app. I would like to validate the users input within textFieldDidEndEditing() in order to provide instant feedback to the user if something is wrong. Each textField needs different validation, eg one will confirm the input is a valid email, another will confirm valid date of birth.

I have tried many design patterns to make this clear flexible but none of them seem possible in swift. I was wondering if anyone has a good solution for this?

I want to avoid something bad like this:

func textFieldDidEndEditing(textfield: UItextField) { 
    if textfield = emailTextBox {
        if validEmail(textfield.text) {
            textfield.shadowColor = blue
        } else {
            textfield.shadowColor = red
        }
    }
    if textfield = dateofBirthTextBox {
        if validDOB(textfield.text) {
            textfield.shadowColor = blue
        } else {
            textfield.shadowColor = red
        }
    }
}

I would like to get as close as possible to this:

func textFieldDidEndEditing(textfield: UItextField) {
    if textfield.isValid {
       textfield.shadowColor = blue
    } else {
       textfield.shadowColor = red
    }
}

I have thought of/tried:

  • extending UItextField with many validation functions
  • extending UItextField with a generic validator function that is overwritten by a subclass and each textField is an subClass
  • Validator protocol that each UItextField subclass implements
  • Validator superclass then get put subclasses into a dictionary with [UItextField:Validator]

I have not been able to implement any of these well because of limitations within Swift and would appreciate any help.

Many thanks

Aucun commentaire:

Enregistrer un commentaire