Run time validation in UItextField
I want to have runtime validation on my UITextField, i.e. when user starts entering data, it should validate and pop up error message if not correct. How do I implement this feature ?
开发者_运维问答textfieldDidChange or textFieldShouldEndEditing can be of any help ?
Any tutorial ?
You can implement the textField:shouldChangeCharactersInRange:replacementString:
method on your text field's delegate, rejecting any characters that are invalid for your textfield. See the UITextFieldDelegate protocol reference for more information.
For example, if you only want to allow entry of decimal numbers, you could use:
- (BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSCharacterSet *nonNumberSet = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
return ([string stringByTrimmingCharactersInSet:nonNumberSet].length > 0);
}
This won't actually pop up an error message if the input is incorrect; instead, it will prevent entry of characters that are incorrect.
If you do want to allow the user to type invalid characters, and them give them an error, you could implement this in the textFieldShouldEndEditing:
method of your delegate.
This is a better solution since it allows backspaces. Taken from :Hugo Larcher's blog
- (BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSCharacterSet *nonNumberSet;
if (textField == self.priceField) //allow decimals
nonNumberSet=[[NSCharacterSet characterSetWithCharactersInString:@"0123456789."] invertedSet];
else
nonNumberSet=[[NSCharacterSet characterSetWithCharactersInString:@"0123456789"] invertedSet];
// allow backspace
if (range.length > 0 && [string length] == 0) {
return YES;
}
// do not allow . at the beggining
if (range.location == 0 && [string isEqualToString:@"."]) {
return NO;
}
// set the text field value manually
NSString *newValue = [[textField text] stringByReplacingCharactersInRange:range withString:string];
newValue = [[newValue componentsSeparatedByCharactersInSet:nonNumberSet] componentsJoinedByString:@""];
textField.text = newValue;
// return NO because we're manually setting the value
return NO;
}
精彩评论