Search code examples
iosuikituitextfielduitextfielddelegate

I need to validate two uitextfields differently. How do I do this?


One text field only takes alphabet characters and the other one is alphanumeric. I have defined shouldChangeCharactersInRange in my ViewController for one of them. Now I don't know where I'm supposed to define the logic for other uitextfield.

Can someone help me understand how this should work?


Solution

  • You have a couple options. If you have created iVars for your text fields, checking which one is calling shouldChangeCharactersInRange is as simple as ==. Below I've also shown that another option would be to assign tags to the text fields and check the tag of the sending text field.

    - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
    {
        //Your first option
        if (textField == myFirstTextField) {
            //
        }else{
            //
        }
        //another option, if you don't want to create iVars you can assign tags to your text fields and do this
        if (textField.tag == 99) {
            //
        }else{
            //
        }
    }