且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何检查UITextField的文本是否是有效的电子邮件?

更新时间:2023-11-29 11:57:46

这将检查UITextField是否有正确的电子邮件。

Add此方法添加到 textFields 委托 ,然后检查要更改的字符是否应该添加。

返回 NO ,具体取决于文本字段当前文本与有效电子邮件地址的比较:

This will check a UITextField for a proper email.
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 fields current text compared to a valid email address:

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

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSCharacterSet *unacceptedInput = nil;
    if ([[textField.text componentsSeparatedByString:@"@"] count] > 1) {
        unacceptedInput = [[NSCharacterSet characterSetWithCharactersInString:[ALPHA_NUMERIC stringByAppendingString:@".-"]] invertedSet];
    } else {
        unacceptedInput = [[NSCharacterSet characterSetWithCharactersInString:[ALPHA_NUMERIC stringByAppendingString:@".!#$%&'*+-/=?^_`{|}~@"]] invertedSet];
    }
    return ([[string componentsSeparatedByCharactersInSet:unacceptedInput] count] <= 1);
}  

要检查文本字段是否为空或不是使用 if(myTextField.text.length> 0){} 在视图控制器中的任何位置。

To check if a text field is empty or not just use if (myTextField.text.length > 0) {} anywhere in your view controller.