该例子主要利用策略模式来判断UITextField是否满足输入要求,比如输入的只能是数字,如果只是数字就没有提示,如果有其他字符则提示出错。验证字母也是一样。
首先,我们先定义一个抽象的策略类iputValidator。代码如下:
InputValidator.h
//
// InputValidator.h
// StrategyDemo
//
// Created by zhanggui on 15/8/7.
// Copyright (c) 2015年 zhanggui. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
static NSString * const InputValidationErrorDomain = @"InputValidationErrorDomain";
@interface InputValidator : NSObject
//实际验证策略的存根方法
-(BOOL)validateInput:(UITextField *)input error:(NSError **)error;
@end
InputValidator.m
//
// InputValidator.m
// StrategyDemo
//
// Created by zhanggui on 15/8/7.
// Copyright (c) 2015年 zhanggui. All rights reserved.
//
#import "InputValidator.h"
@implementation InputValidator
-(BOOL)validateInput:(UITextField *)input error:(NSError **)error
{
if (error) {
*error = nil;
}
return NO;
}
@end
这个就是一个策略基类,然后我们去创建两个子类NumericInputValidator和AlphaInputValidator。具体代码如下:
NumericIputValidator.h
//
// NumericInputValidator.h
// StrategyDemo
//
// Created by zhanggui on 15/8/7.
// Copyright (c) 2015年 zhanggui. All rights reserved.
//
#import "InputValidator.h"
@interface NumericInputValidator : InputValidator
-(BOOL)validateInput:(UITextField *)input error:(NSError **)error;
@end
NumericIputValidator.m
//
// NumericInputValidator.m
// StrategyDemo
//
// Created by zhanggui on 15/8/7.
// Copyright (c) 2015年 zhanggui. All rights reserved.
//
#import "NumericInputValidator.h"
@implementation NumericInputValidator
-(BOOL)validateInput:(UITextField *)input error:(NSError **)error
{
NSError *regError = nil;
//使用配置的NSRegularExPRession对象,检查文本框中数值型的匹配次数。
//^[0-9]*$:意思是从行的开头(表示为^)到结尾(表示为$)应该有数字集(标示为[0-9])中的0或者更多个字符(表示为*)
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^[0-9]*$" options:NSRegularExpressionAnchorsMatchLines error:®Error];
NSUInteger numberOfMatches = [regex numberOfMatchesInString:[input text] options:NSMatchingAnchored range:NSMakeRange(0, [[input text] length])];
//如果没有匹配,就返回错误和NO
if (numberOfMatches==0) {
if (error != nil) {
NSString *description = NSLocalizedString(@"Input Validation Faild", @"");
NSString *reason = NSLocalizedString(@"The input can contain only numerical values", @"");
NSArray *objArray = [NSArray arrayWithObjects:description,reason, nil];
NSArray *keyArray = [NSArray arrayWithObjects:NSLocalizedDescriptionKey,NSLocalizedFailureReasonErrorKey ,nil];
NSDictionary *userInfo = [NSDictionary dictionaryWithObjects:objArray forKeys:keyArray];
*error = [NSError errorWithDomain:InputValidationErrorDomain code:1001 userInfo:userInfo];
}
return NO;
}
return YES;
}
@end
AlphaInputValidator.h
//
// AlphaInputValidator.h
// StrategyDemo
//
// Created by zhanggui on 15/8/7.
// Copyright (c) 2015年 zhanggui. All rights reserved.
//
#import "InputValidator.h"
@interface AlphaInputValidator : InputValidator
- (BOOL)validateInput:(UITextField *)input error:(NSError **)error;
@end
AlphaInputValidator.m
//
// AlphaInputValidator.m
// StrategyDemo
//
// Created by zhanggui on 15/8/7.
// Copyright (c) 2015年 zhanggui. All rights reserved.
//
#import "AlphaInputValidator.h"
@implementation AlphaInputValidator
-(BOOL)validateInput:(UITextField *)input error:(NSError **)error
{
NSError *regError = nil;
//使用配置的NSRegularExpression对象,检查文本框中数值型的匹配次数。
//^[0-9]*$:意思是从行的开头(表示为^)到结尾(表示为$)应该有数字集(标示为[0-9])中的0或者更多个字符(表示为*)
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^[a-zA-Z]*$" options:NSRegularExpressionAnchorsMatchLines error:®Error];
NSUInteger numberOfMatches = [regex numberOfMatchesInString:[input text] options:NSMatchingAnchored range:NSMakeRange(0, [[input text] length])];
//如果没有匹配,就返回错误和NO
if (numberOfMatches==0) {
if (error != nil) {
NSString *description = NSLocalizedString(@"Input Validation Faild", @"");
NSString *reason = NSLocalizedString(@"The input can contain only letters ", @"");
NSArray *objArray = [NSArray arrayWithObjects:description,reason, nil];
NSArray *keyArray = [NSArray arrayWithObjects:NSLocalizedDescriptionKey,NSLocalizedFailureReasonErrorKey ,nil];
NSDictionary *userInfo = [NSDictionary dictionaryWithObjects:objArray forKeys:keyArray];
*error = [NSError errorWithDomain:InputValidationErrorDomain code:1002 userInfo:userInfo];
}
return NO;
}
return YES;
}
@end
他们两个都是InputValidator的子类。然后再定义一个CustomTextField:
CustomTextField.h
//
// CustomTextField.h
// StrategyDemo
//
// Created by zhanggui on 15/8/7.
// Copyright (c) 2015年 zhanggui. All rights reserved.
//
#import <UIKit/UIKit.h>
@class InputValidator;
@interface CustomTextField : UITextField
@property(nonatomic,strong)InputValidator *inputValidator;
-(BOOL)validate;
@end
CustomTextField.m
//
// CustomTextField.m
// StrategyDemo
//
// Created by zhanggui on 15/8/7.
// Copyright (c) 2015年 zhanggui. All rights reserved.
//
#import "CustomTextField.h"
#import "InputValidator.h"
@implementation CustomTextField
-(BOOL)validate {
NSError *error = nil;
BOOL validationResult = [_inputValidator validateInput:self error:&error];
if (!validationResult) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:[error localizedDescription] message:[error localizedFailureReason] delegate:nil cancelButtonTitle:NSLocalizedString(@"OK", @"") otherButtonTitles: nil];
[alertView show];
}
return validationResult;
}
@end
最后在ViewController中测试是否完成验证
ViewController.m
//
// ViewController.m
// StrategyDemo
//
// Created by zhanggui on 15/8/7.
// Copyright (c) 2015年 zhanggui. All rights reserved.
//
#import "ViewController.h"
#import "CustomTextField.h"
#import "NumericInputValidator.h"
#import "AlphaInputValidator.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
_numberTextField.inputValidator = [NumericInputValidator new];
_letterTextField.inputValidator = [AlphaInputValidator new];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - ValidButtonMehtod
- (IBAction)validNumAction:(id)sender {
[_numberTextField validate];
}
- (IBAction)validLetterAction:(id)sender {
[_letterTextField validate];
}
@end
结果:当我们输入的不满足条件的时候就会显示提示信息,而满足条件就不会有任何提示。