摘要:[IOS] 驗證字串至少包含英文和數字
有時候在App中提供註冊會員功能時,我們必須驗證使用者所填寫的密碼字串。
如果只是想用來找查某個字串裡面是否有哪些字,我建議可以使用 NSString 的 rangeOfString 方法
rangeOfString 會返回一個 NSRange,告訴你想找碴的字的位於哪個 location和 length
範例:
NSString *tMySentence = @"My name is Cathy.";
NSString *tMyName = @"Cathy";
NSRange tRange = [tMySentence rangeOfString:tMyName];
NSLog(@"\"%@\" is located at %d in \"%@\" sentence.",tMyName,tRange.location,tMySentence);
結果:
"Cathy" is located at 11 in "My name is Cathy." sentence.
注意:
NSRange的location從0開始
若我把要找的字串改成小寫的c
NSString *tMySentence = @"My name is Cathy.";
NSString *tMyName = @"cathy";
NSRange tRange = [tMySentence rangeOfString:tMyName];
NSLog(@"\"%@\" is located at %d in \"%@\" sentence.",tMyName,tRange.location,tMySentence);
則印出
"cathy" is located at 2147483647 in "My name is Cathy." sentence.
判斷有沒有找到想找的字串
if (tRange.location == NSNotFound)
{
//u can't found my name :p
}
若需要用到比較複雜的字串比對檢查
可以使用 NSRegularExpression
我現在想比對密碼字串是否包含至少一個英文和數字
範例:
//數字條件
NSRegularExpression *tNumRegularExpression = [NSRegularExpression regularExpressionWithPattern:@"[0-9]" options:NSRegularExpressionCaseInsensitive error:nil];
//符合數字條件的有幾個字元
int tNumMatchCount = [tNumRegularExpression numberOfMatchesInString:pPassword
options:NSMatchingReportProgress
range:NSMakeRange(0, pPassword.length)];
//英文字條件
NSRegularExpression *tLetterRegularExpression = [NSRegularExpression regularExpressionWithPattern:@"[A-Za-z]" options:NSRegularExpressionCaseInsensitive error:nil];
//符合英文字條件的有幾個字元
int tLetterMatchCount = [tLetterRegularExpression numberOfMatchesInString:pPassword options:NSMatchingReportProgress range:NSMakeRange(0, pPassword.length)];
if (tNumMatchCount == pPassword.length)
{
//全部符合數字,表示沒有英文
return ConfirmPasswordResult_HaveNoChar;
}
else if (tLetterMatchCount == pPassword.length)
{
//全不符合英文,表示沒有數字
return ConfirmPasswordResult_HaveNoNum;
}
else if (tNumMatchCount + tLetterMatchCount == pPassword.length)
{
//符合英文和符合數字條件的相加等於密碼長度
return ConfirmPasswordResult_Success;
}
else
{
//可能包含標點符號的情況,或是包含非英文的文字,這裡再依照需求詳細判斷想呈現的錯誤
}
目前只有想到這個可以正確的判斷包含英文和數字的字串
若有發現更好的解法再放上來讓大家研究