1,首先我们需要控制输入字符的验证,比如(中国的)手机号不能超过11位人,验证码为4/6位 密码多少位等。。。
[_nameText addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
[_phoneText addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
[_textField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
实现textFieldDidChange方法,判断中文下输入
pragma mark – 输入框观察者事件
- (void)textFieldDidChange:(UITextField *)textField {
NSInteger kMaxLength = 10 ;
NSString *toBeString = textField.text;
if (textField == _phoneText) {
kMaxLength = 11;
}else if (textField == _nameText){
kMaxLength = 12;
}else if (textField == _textField){
kMaxLength = 5;
}
NSString *lang = [[UIApplication sharedApplication]textInputMode].primaryLanguage; //ios7之前使用[UITextInputMode currentInputMode].primaryLanguage
if ([lang isEqualToString:@"zh-Hans"]) { //中文输入
UITextRange *selectedRange = [textField markedTextRange];
//获取高亮部分
UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
if (!position) {// 没有高亮选择的字,则对已输入的文字进行字数统计和限制
if (toBeString.length > kMaxLength) {
textField.text = [toBeString substringToIndex:kMaxLength];
}
}
}else{//中文输入法以外的直接对其统计限制即可,不考虑其他语种情况
if (toBeString.length > kMaxLength) {
textField.text = [toBeString substringToIndex:kMaxLength];
}
}
self.sureBtn.userInteractionEnabled = YES;
}
3,提交的时候用正则表达式验证:
if ([self.phoneText.text length] == 0) {
[DZTools showNOHud:LocalizedString(@"请输入电话号码") delay:1];
return;
}
///13456789{9} 正则表达式
if (![self.phoneText.text isTelephone]) {
[DZTools showNOHud:LocalizedString(@"请输入正确的电话号码") delay:1];
return;
}
网友评论