兩個實務上很常被需要的輸入驗證:使用者設定暱稱時不允許輸入 emoji(某些資料庫編碼或後端系統會出問題),以及註冊表單的 Email 格式檢查。
原理是遍歷字串的每個「組合字元序列」,再依 Unicode 區段判斷該字元是否落在 emoji 的碼點範圍內。這裡同時處理了 surrogate pair(代理對)與單一碼點兩種情況。
- (BOOL)stringContainsEmoji:(NSString *)string
{
__block BOOL returnValue = NO;
[string enumerateSubstringsInRange:NSMakeRange(0, [string length])
options:NSStringEnumerationByComposedCharacterSequences
usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
const unichar hs = [substring characterAtIndex:0];
if (0xd800 <= hs && hs <= 0xdbff) {
// 高位代理:需再看一個字元組成完整碼點
if (substring.length > 1) {
const unichar ls = [substring characterAtIndex:1];
const int uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
if (0x1d000 <= uc && uc <= 0x1f77f) {
returnValue = YES;
*stop = YES;
}
}
} else if (substring.length > 1) {
// 組合型表情,例如帶 0x20E3 的 keycap 序列
const unichar ls = [substring characterAtIndex:1];
if (ls == 0x20e3) {
returnValue = YES;
*stop = YES;
}
} else {
// 非代理對的單碼點表情
if (0x2100 <= hs && hs <= 0x27ff) {
returnValue = YES;
} else if (0x2B05 <= hs && hs <= 0x2b07) {
returnValue = YES;
} else if (0x2934 <= hs && hs <= 0x2935) {
returnValue = YES;
} else if (0x3297 <= hs && hs <= 0x3299) {
returnValue = YES;
} else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030
|| hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b || hs == 0x2b50) {
returnValue = YES;
}
if (returnValue) {
*stop = YES;
}
}
}];
return returnValue;
}
使用時機很簡單:在文字輸入欄的 shouldChangeCharactersInRange 回調中呼叫它,若回傳 YES 就直接回傳 NO 拒絕這次輸入,使用者會感覺「這個欄位打不出表情」。
用 NSPredicate 搭配正則表達式,是最簡潔的寫法:
- (BOOL)isValidateEmail:(NSString *)email
{
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:email];
}
這條正則拆開來看:@ 之前允許大小寫字母、數字與 . _ % + -;@ 之後是網域;最後是 2 到 4 個字母的頂級域名。
.museum、.travel、.technology 等更長的頂級域名,建議放寬為 {2,}。email.stringByTrimmingCharactersInSet: 能避免大量誤判。