TextField Validation With Regular Expression

后端 未结 4 1874
没有蜡笔的小新
没有蜡笔的小新 2020-12-12 17:29

I need help with code that looks at a textfield make sure it starts with either a (+ or -) then has 3 integers after it.

So valid data looks like +234 or -888

4条回答
  •  伪装坚强ぢ
    2020-12-12 18:27

    Validate Email id or Phone number using Regular Expression

    Ddelegate methods:

    - (BOOL)textFieldShouldReturn:(UITextField *)aTextField
    {
        [aTextField resignFirstResponder];
        return YES;
    }
    
    - (BOOL)textFieldShouldEndEditing:(UITextField *)aTextField
    {
        return [self validateEmail:aTextField.text]; // Change validateEmail to validatePhone for phone validation.
    }
    

    Returns YES or NO whether the input is valid or not:

    - (BOOL) validateEmail: (NSString *) candidate {
        NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"; 
        NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex]; 
    
        return [emailTest evaluateWithObject:candidate];
    }
    
    - (BOOL) validatePhone: (NSString *) candidate {
        NSString *phoneRegex = @"^+(?:[0-9] ?){6,14}[0-9]$"; 
        NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", phoneRegex]; 
    
        return [phoneTest evaluateWithObject:candidate];
    }
    

提交回复
热议问题