1
我想驗證長度並僅限制iOS中的數字,字母數字和字母字符,任何人都可以幫助我實現這一點。如何驗證長度並將文本字段限制爲僅適用於iOS中的數字,字母數字和字母字符
我想驗證長度並僅限制iOS中的數字,字母數字和字母字符,任何人都可以幫助我實現這一點。如何驗證長度並將文本字段限制爲僅適用於iOS中的數字,字母數字和字母字符
找到最好的方法來解決這個問題。工程就像一個冠軍:)
.m文件裏面
//#define CHARACTERS @" ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
//#define CHARACTERS_NUMBERS [CHARACTERS stringByAppendingString:@"1234567890"]
///// Inside shouldChangeCharactersInRange
///////////>>>>>>>>>>>>>>>>>>
if(textField== txtFldAlpha)
{
//Alpha only
NSUInteger newLength = [textField.text length] + [string length] - range.length;
NSCharacterSet *unacceptedInput =
[[NSCharacterSet characterSetWithCharactersInString:CHARACTERS] invertedSet];
// Create array of strings from incoming string using the unacceptable
// characters as the trigger of where to split the string.
// If array has more than one entry, there was at least one unacceptable character
if ([[string componentsSeparatedByCharactersInSet:unacceptedInput] count] > 1)
return NO;
else
return YES&&(newLength < 26);
return YES;
}
///////////<<<<<<<<<<<<<<<<<<
///////////>>>>>>>>>>>>>>>>>>
if(textField==txtFldNumeric)
{
//Num only
NSUInteger newLength = [textField.text length] + [string length] - range.length;
NSCharacterSet *nonNumberSet = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
if ([[string componentsSeparatedByCharactersInSet:nonNumberSet] count] > 1)
return NO;
else
return YES&&(newLength < 6);
return YES;
}
///////////<<<<<<<<<<<<<<<<<<
///////////>>>>>>>>>>>>>>>>>>
if(textField==txtFieldNumAlphaSpecial)
{
//Num,Alpha,Special field
NSUInteger newLength = [textField.text length] + [string length] - range.length;
return (newLength > 50) ? NO : YES;
}
///////////<<<<<<<<<<<<<<<<<<
可以形成正則表達式的字符串,並使用它。請在下面找到一個代碼示例,僅允許字母和空格。
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSString *stringPlace = @"[a-z A-Z]*";
NSPredicate *testPlace = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", stringPlace];
BOOL matches = [testPlace evaluateWithObject:string];
// if it does not match the regular expression and more than 5 characters
if (!matches && string.length > 5)
{
return NO;
}
return YES;
}
+1。更快,更優雅的解決方案。 – tipycalFlow 2012-09-11 04:47:25