IOS中使用正则表达式判断表单输入

2014-12-24  本文已影响388人  SHUTUP

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

上一篇 下一篇

猜你喜欢

热点阅读