- 我最近的项目中需要给服务器报送数据,但是在报送前需要先判断用户填写数据的正确性。我对oc不是特别熟悉,没有发现比较方便的方法,因此将我的解决方法记录下来,给需要的人,当然如果你有好方法,欢迎留言!
关于正则表达式,请自行google!
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