-->

iOS TextField Validation

2020-06-03 09:19发布

问题:

I need a way to ensure that phone numbers have 10 digits with no other characters ie () - and make sure that email addresses are valid emails (formatted correctly).

Is there any library that can't make this easy for me so I don't have to write regular expressions.

回答1:

This will check a UITextField for a proper email and phone number of 10 digits or less.
Add this method to the textFields delegate then check if the characters it is about to change should be added or not.
Return YES or NO depending on the text field, how many characters are currently in it, and what characters it wants to add:

#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:@".!#$%&'*+-/=?^_`{|}~@"]] 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);
}  

Also, check out these 2 articles:
Auto-formatting phone number UITextField on the iPhone
PhoneNumberFormatter.



回答2:

Here's a simple way of ensuring phonenumber length in the UIViewController that has the text field in it's view.

- (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];
}

For emails I suppose you want to check against a regexp when it loses focus.



回答3:

Here's Simple Example for UITextField Validation while type in keyboard other characters not displaying

-(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;
}
}