iOS TextField Validation

前端 未结 3 2055
南方客
南方客 2021-02-09 07:50

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 t

3条回答
  •  失恋的感觉
    2021-02-09 08:34

    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.

提交回复
热议问题