Pregunta

I have a UITextField where the user can enter in their phone number. I need the phone number to be in the following format: 5567289223 and not like this with an extra 1 at the beginning: 15567289223.

I already have an if statement setup so if the number is greater than 10 digits or less than 10 digits it will throw an error.

The only final problem I don't know how to solve is if the user tries putting an extra 1 in the beginning of the phone number.

I need to setup an if statement so that if the first character in the phone number is a "1" we will throw an error, or an even easier possible solution would be to use shouldChangeCharactersInRange so that if it's the first number they are typing in the UITextField then it cannot be a 1.

Someone gave me this solution earlier for controlling which characters are allowed to be typed into a UITextField: https://stackoverflow.com/a/22265084/3344977

I have been trying to modify it so that it will not allow the number "1" to be the first number typed into the UITextField but I cannot get it to work properly.

Any help is greatly appreciated.

¿Fue útil?

Solución

I have modified the example you want to use as per your need, you can check it out

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if(textField==self.testTextField&&range.location==0)
{
    if ([string hasPrefix:@"1"])
    {
        return NO;
    }
}

return YES;
}

Otros consejos

See this answer,

UITextField text change event

i would setup an event handler like how it's mentioned in that example. and then an if statement inside the selector:

if([textField.text length] == 1 && [textField.text isEqualToString:@"1"]){

     //Do something.
}

Hope this helps

For Swift

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

 if textField == self.txtFieldName && range.location == 0
    {
        if string.hasPrefix("1"){
            return false
        }
    }
    return true

}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top