- 我最近的項目中需要給服務(wù)器報送數(shù)據(jù),但是在報送前需要先判斷用戶填寫數(shù)據(jù)的正確性。我對oc不是特別熟悉,沒有發(fā)現(xiàn)比較方便的方法,因此將我的解決方法記錄下來,給需要的人,當(dāng)然如果你有好方法,歡迎留言!
關(guān)于正則表達式,請自行g(shù)oogle!
NSString+FormValidation.h
#import <Foundation/Foundation.h>
@interface NSString (FormValidation)
//判斷是否在0-99之間
- (BOOL)isValidBetween0_99;
//判斷是否在0-999之間
- (BOOL)isValidBetween0_999;
//判斷是否在1-15之間
- (BOOL)isValidBetween1_15;
//判斷是否在0-99.9之間(支持 ".",".1"等)
- (BOOL)isValidBetween0_0_to_99_9;
@end
NSString+FormValidation.m
#import "NSString+FormValidation.h"
@implementation NSString (FormValidation)
- (BOOL)isValidBetween0_99 {
NSError* error=nil;
NSString* regex=@"^\\d{1,2}$";
NSRegularExpression* reg=[NSRegularExpression regularExpressionWithPattern:regex options:NSRegularExpressionCaseInsensitive error:&error];
NSArray* match =[reg matchesInString:self options:0 range:NSMakeRange(0, self.length)];
NSLog(@"match count %li",match.count);
if (match.count!=0) {
return YES;
}
return NO;
}
- (BOOL)isValidBetween0_999 {
NSError* error=nil;
NSString* regex=@"^\\d{1,3}$";
NSRegularExpression* reg=[NSRegularExpression regularExpressionWithPattern:regex options:NSRegularExpressionCaseInsensitive error:&error];
NSArray* match =[reg matchesInString:self options:0 range:NSMakeRange(0, self.length)];
NSLog(@"match count %li",match.count);
if (match.count!=0) {
return YES;
}
return NO;
}
- (BOOL)isValidBetween1_15
{
NSError* error=nil;
NSString* regex=@"^[0-1][0-5]$|^\\d$";
NSRegularExpression* reg=[NSRegularExpression regularExpressionWithPattern:regex options:NSRegularExpressionCaseInsensitive error:&error];
NSArray* match =[reg matchesInString:self options:0 range:NSMakeRange(0, self.length)];
NSLog(@"match count %li",match.count);
if (match.count!=0) {
return YES;
}
return NO;
}
- (BOOL)isValidBetween0_0_to_99_9
{
NSError* error=nil;
NSString* regex=@"^\\d?\\.\\d?$|^\\d{2}\\.\\d?$|^\\d{1,2}$";
NSRegularExpression* reg=[NSRegularExpression regularExpressionWithPattern:regex options:NSRegularExpressionCaseInsensitive error:&error];
NSArray* match =[reg matchesInString:self options:0 range:NSMakeRange(0, self.length)];
NSLog(@"match count %li",match.count);
if (match.count!=0) {
return YES;
}
return NO;
}
@end