表單驗證幾乎每個 App 都要寫一次,而且散落在各處、標準不一。比較好的做法是把規則集中到一個驗證器類別裡,用列舉型別指定要驗證哪一種,對外只暴露一個方法。
#import <Foundation/Foundation.h>
typedef enum {
IdentifierTypeKnown = 0,
IdentifierTypeZipCode, // 1 郵遞區號
IdentifierTypeEmail, // 2 電子郵件
IdentifierTypePhone, // 3 手機號碼
IdentifierTypeUnicomPhone, // 4 聯通號碼
IdentifierTypeQQ, // 5 QQ 號
IdentifierTypeNumber, // 6 純數字
IdentifierTypeString, // 7 非空字串
IdentifierTypeIdentifier, // 8 身分證字號
IdentifierTypePassort, // 9 護照號碼
IdentifierTypeCreditNumber, // 10 信用卡卡號
IdentifierTypeBirthday // 11 生日
} IdentifierType;
@interface IdentifierValidator : NSObject
+ (BOOL)isValid:(IdentifierType)type value:(NSString *)value;
@end
先準備兩個底層輔助函式,後續多數規則都會用到:
int getIndex(char ch) {
if ((ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'z') ||
(ch >= 'A' && ch <= 'Z') || ch == '_') return 0;
if (ch == '@') return 1;
if (ch == '.') return 2;
return -1;
}
BOOL isNumber(char ch) {
return (ch >= '0' && ch <= '9') ? TRUE : FALSE;
}
郵遞區號(台灣為 3 或 5 位數字,此處以 6 位為例):
+ (BOOL)isValidZipcode:(NSString *)value {
const char *cvalue = [value UTF8String];
int len = strlen(cvalue);
if (len != 6) return FALSE;
for (int i = 0; i < len; i++) {
if (!(cvalue[i] >= '0' && cvalue[i] <= '9')) return FALSE;
}
return TRUE;
}
電子郵件(用 NSPredicate 跑正則,比手寫狀態機好維護):
+ (BOOL)validateEmail:(NSString *)candidate {
if ([[candidate componentsSeparatedByString:@"."] count] >= 4)
return FALSE;
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)isValidPhone:(NSString *)value {
const char *cvalue = [value UTF8String];
if (strlen(cvalue) != 11) return FALSE;
if (![IdentifierValidator isValidNumber:value]) return FALSE;
NSString *pre = [value substringToIndex:2];
return ([pre isEqualToString:@"13"] ||
[pre isEqualToString:@"15"] ||
[pre isEqualToString:@"18"]) ? TRUE : FALSE;
}
身分證字號(含第二代的檢查碼驗證):
const int factor[] = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 }; // 加權因子
const int checktable[] = { 1, 0, 10, 9, 8, 7, 6, 5, 4, 3, 2 }; // 檢查碼對照表
+ (BOOL)isValidIdentifier:(NSString *)value {
const int LENGTH = 18;
const char *str = [[value lowercaseString] UTF8String];
NSInteger length = strlen(str);
BOOL result = (15 == length || LENGTH == length);
if (result) {
for (NSInteger i = 1; i < length - 1; i++) {
if (!(str[i] >= '0' && str[i] <= '9')) { result = FALSE; break; }
}
if (result && LENGTH == length) {
if (!((str[17] >= '0' && str[17] <= '9') || str[17] == 'x'))
result = FALSE;
}
if (result && length == LENGTH) {
int *ids = malloc(sizeof(int) * LENGTH);
for (int i = 0; i < LENGTH; i++) ids[i] = str[i] - 48;
int checksum = 0;
for (int i = 0; i < LENGTH - 1; i++) checksum += ids[i] * factor[i];
if (ids[17] == checktable[checksum % 11] ||
(str[17] == 'x' && checktable[checksum % 11] == 10))
result = TRUE;
else
result = FALSE;
free(ids);
}
}
return result;
}
信用卡卡號(依發卡行前綴判斷卡別,再用 Luhn 演算法驗檢查碼):
/*
* 常見發卡機構前綴與長度
* Diner's Club 300xxx-305xxx, 3095xx, 36xxxx, 38xxxx 14
* American Express 34xxxx, 37xxxx 15
* VISA 4xxxxx 13, 16
* MasterCard 51xxxx-55xxxx 16
* JCB 3528xx-358x 16
* Discover 6011xx 16
* 銀聯 622126-622925 16
*
* Luhn 演算法:偶數位數值 ×2,若大於 10 則減 9,全部相加後
* 若總和不是 10 的倍數,卡號即為不合法。
*/
+ (BOOL)isValidCreditNumber:(NSString *)value {
NSInteger length = [value length];
if (length < 13) return FALSE;
if (![IdentifierValidator isValidNumber:value]) return FALSE;
NSInteger two = [[value substringWithRange:NSMakeRange(0, 2)] integerValue];
NSInteger three = [[value substringWithRange:NSMakeRange(0, 3)] integerValue];
NSInteger four = [[value substringWithRange:NSMakeRange(0, 4)] integerValue];
if (((three >= 300 && three <= 305) || four == 3095 ||
two == 36 || two == 38) && length != 14) return FALSE;
if ([value hasPrefix:@"4"] && !(length == 13 || length == 16)) return FALSE;
if (two >= 51 && two <= 55 && length != 16) return FALSE;
if (([value hasPrefix:@"34"] || [value hasPrefix:@"37"]) && length != 15) return FALSE;
if ([value hasPrefix:@"6011"] && length != 16) return FALSE;
NSInteger begin = [[value substringWithRange:NSMakeRange(0, 6)] integerValue];
if (begin >= 622126 && begin <= 622925 && length != 16) return FALSE;
// Luhn 檢查
NSInteger checkSum = 0, index, leftIndex;
if (length % 2 == 0) { index = 0; leftIndex = 1; }
else { index = 1; leftIndex = 0; }
while (index < length) {
NSInteger digitValue =
[[value substringWithRange:NSMakeRange(index, 1)] integerValue] * 2;
checkSum += (digitValue >= 10) ? (digitValue / 10 + digitValue % 10) : digitValue;
digitValue = [[value substringWithRange:NSMakeRange(leftIndex, 1)] integerValue];
checkSum += digitValue;
index += 2; leftIndex += 2;
}
return (checkSum % 10 == 0) ? TRUE : FALSE;
}
生日(用 NSDateFormatter 反解,能順便擋掉 2 月 30 日這類不存在的日期):
+ (BOOL)isValidBirthday:(NSString *)birthday {
if (!birthday || [birthday length] != 8) return FALSE;
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyyMMdd"];
return [formatter dateFromString:birthday] ? TRUE : FALSE;
}
最後用 switch 把規則串起來,呼叫端只需一行:
+ (BOOL)isValid:(IdentifierType)type value:(NSString *)value
{
if (!value ||
[[value stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceCharacterSet]] isEqualToString:@""])
return FALSE;
switch (type) {
case IdentifierTypeZipCode: return [IdentifierValidator isValidZipcode:value];
case IdentifierTypeEmail: return [IdentifierValidator validateEmail:value];
case IdentifierTypePhone: return [IdentifierValidator isValidPhone:value];
case IdentifierTypeUnicomPhone: return [IdentifierValidator isChinaUnicomPhoneNumber:value];
case IdentifierTypeQQ: return [IdentifierValidator isValidNumber:value];
case IdentifierTypeNumber: return [IdentifierValidator isValidNumber:value];
case IdentifierTypeString: return [IdentifierValidator isValidString:value];
case IdentifierTypeIdentifier: return [IdentifierValidator isValidIdentifier:value];
case IdentifierTypePassort: return [IdentifierValidator isValidPassport:value];
case IdentifierTypeCreditNumber: return [IdentifierValidator isValidCreditNumber:value];
case IdentifierTypeBirthday: return [IdentifierValidator isValidBirthday:value];
default: return TRUE;
}
}
實務上要提醒兩點:一是電信商號段會隨時間調整,寫死 13x/15x/18x 遲早需要更新,建議把號段規則抽成設定檔;二是這些規則只用於「格式是否正確」的前端提示,真正的唯一性與合法性仍須由後端驗證,前端驗證只是為了改善使用者體驗。