此框架允许您以方便的方式验证文本字段和文本视图的输入。
从上述链接克隆项目。
US2Validator *validator = [[US2Validator alloc] init];
US2ConditionAlphabetic *condition = [[US2ConditionAlphabetic alloc] init];
[validator addCondition:condition];
[condition release];
US2ConditionCollection *conditionCollection1 = [validator checkConditions:@"HelloWorld"];
US2ConditionCollection *conditionCollection2 = [validator checkConditions:@"Hello World 123"];
BOOL isValid = conditionCollection1 == nil; // isValid == YES
isValid = conditionCollection2 == nil; // isValid == NO
// What went wrong?
NSLog(@"conditionCollection2: %@", conditionCollection2);
US2ValidatorTextField *firstNameTextField = [[US2ValidatorTextField alloc] init];
firstNameTextField.validator = [[[MyProjectValidatorName alloc] init] autorelease];
firstNameTextField.shouldAllowViolation = YES;
firstNameTextField.validateOnFocusLossOnly = YES;
firstNameTextField.placeholder = @"Enter first name";
firstNameTextField.validatorUIDelegate = self;
[_textUICollection addObject:firstNameTextField];
[firstNameTextField release];
创建接口。
#import <Foundation/Foundation.h>
#import "US2Condition.h"
@interface MyProjectConditionName : US2Condition
@end
创建实现。
#import "MyProjectConditionName.h"
@implementation MyProjectConditionName
- (BOOL)check:(NSString *)string
{
if (nil == string)
string = [NSString string];
self.regexString = @"[a-zA-Z .-]";
return [super check:string];
}
#pragma mark - Allow violation
- (BOOL)shouldAllowViolation
{
return YES;
}
#pragma mark - Localization
- (NSString *)localizedViolationString
{
return @"Not a valid name";
}
@end
创建接口。
#import <Foundation/Foundation.h>
#import "US2Validator.h"
#pragma mark - Validator interface
@interface MyProjectValidatorName : US2Validator
{
}
@end
创建实现。
#import "MyProjectValidatorName.h"
#import "MyProjectConditionName.h"
#import "US2ConditionRange.h"
@implementation MyProjectValidatorName
#pragma mark - Initialization
- (id)init
{
self = [super init];
if (self)
{
[self addCondition:[[[MyProjectConditionName alloc] init] autorelease]];
US2ConditionRange *rangeCondition = [[[US2ConditionRange alloc] init] autorelease];
rangeCondition.range = NSMakeRange(2, UINT16_MAX);
rangeCondition.shouldAllowViolation = YES;
[self addCondition:rangeCondition];
}
return self;
}
@end