2011-10-05 15 views
7

Necesito una forma de asegurar que los números de teléfono tengan 10 dígitos sin otros caracteres, es decir() - y asegúrese de que las direcciones de correo electrónico sean válidas (formateadas correctamente).iOS FieldField Validation

¿Hay alguna biblioteca que no me lo pueda facilitar así que no tengo que escribir expresiones regulares?

Respuesta

17

Esto comprobará un UITextField para un correo electrónico y número de teléfono correctos de 10 dígitos o menos.
Agregue este método al textFields delegate y luego verifique si los caracteres que está a punto de cambiar deben agregarse o no.
Volver YES o NO dependiendo del campo de texto, el número de caracteres se encuentran actualmente en ella, y lo que los personajes que quiere añadir:

#define ALPHA     @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" 
#define NUMERIC     @"1234567890" 
#define ALPHA_NUMERIC   ALPHA NUMERIC 

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { 
    NSCharacterSet *unacceptedInput = nil; 
    switch (textField.tag) { 
     // Assuming EMAIL_TextField.tag == 1001 
     case 1001: 
      if ([[textField.text componentsSeparatedByString:@"@"] count] > 1) 
       unacceptedInput = [[NSCharacterSet characterSetWithCharactersInString:[ALPHA_NUMERIC stringByAppendingString:@".-"]] invertedSet]; 
      else 
       unacceptedInput = [[NSCharacterSet characterSetWithCharactersInString:[ALPHA_NUMERIC stringByAppendingString:@".!#$%&'*+-/=?^_`{|}[email protected]"]] invertedSet]; 
      break; 
     // Assuming PHONE_textField.tag == 1002 
     case 1002: 
      if (textField.text.length + string.length > 10) { 
       return NO; 
      } 
      unacceptedInput = [[NSCharacterSet decimalDigitCharacterSet] invertedSet]; 
      break; 
     default: 
      unacceptedInput = [[NSCharacterSet illegalCharacterSet] invertedSet]; 
      break; 
    } 
    return ([[string componentsSeparatedByCharactersInSet:unacceptedInput] count] <= 1); 
} 

Además, echa un vistazo a estos 2 artículos:
Auto-formatting phone number UITextField on the iPhone
PhoneNumberFormatter.

+0

Se ve bien, no he mirado en el campo de texto delegado antes. – sunkencity

+0

chown, esto funciona muy bien, pero no parece manejar eventos clave de eliminación. Devuelve NO si el teléfono es> = 10, por lo tanto, no cambia al eliminar – spentak

+0

Oh, estás en lo cierto. Reemplazar 'if (textField.text.length> = 10)' con 'if (textField.text.length + string.length> 10)' – chown

3

Aquí hay una manera simple de asegurar la longitud del número de teléfono en el UIViewController que tiene el campo de texto en su vista.

- (void)valueChanged:(id)sender 
{ 
    if ([[[self phoneNumberField] text] length] > 10) { 
     [[self phoneNumberField] setText:[[[self phoneNumberField] text] 
      substringToIndex:10]]; 
    } 
} 

- (void) viewWillAppear:(BOOL)animated 
{ 
    [[self phoneNumberField] addTarget:self 
          action:@selector(valueChanged:) 
          forControlEvents:UIControlEventEditingChanged]; 
} 

Para mensajes de correo electrónico que supongo que desea comprobar contra una expresión regular cuando se pierde el foco.

0

Aquí es sencillo ejemplo para UITextField Validación mientras que el tipo de teclado en otros caracteres no se muestran

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string 
{ 
//UITextField *tf_phonenumber,*tf_userid; 
if (textField.text<=10) { 
char c=*[string UTF8String]; 
if (tf_phonenumber==textField)  //PhoneNumber /Mobile Number 
{ 
    if ((c>='0' && c<='9')||(c==nil)) { 
     return YES; 
    } 
    else 
     return NO; 
} 
if (tf_userid==textField)   //UserID validation 
{ 
    if ((c>='a' && c<='z')||(c>='A' && c<='Z')||(c==' ')||(c==nil)) { 
     return YES; 
    } 
    else 
     return NO; 
} 
    return YES; 
} 
else{ 
    return NO; 
} 
}