Text Validation - user can only select a number once
I am trying to create a questionnaire, in开发者_运维百科 which the user shall rate statements from 1-7.
The user rates the statements by filling UITextFields
with a value between 1-7.
I have made it so that the user can only write in values between 1-7 and that they only can write one character per textfield.
What I want to do now is to prevent the user from using that value more than once.
This is the code that I have so far.
#define CHARACTERS @"1234567"
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
// These are the characters that are ~not~ acceptable
NSCharacterSet *unacceptedInput = [[NSCharacterSet characterSetWithCharactersInString:CHARACTERS] invertedSet];
NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
if (([[string componentsSeparatedByCharactersInSet:unacceptedInput] count] >1 ) | ([newString length] > 1) )
return NO;
else
return YES;
}
I would use a dictionary. Whenever a number is chosen in a textfield, check if the dictionary has that value. If it doesn't have the value, the value entered is correct. Add the entry into the dictionary now and then let the user proceed to the next textfield. If you repeat this process for all the textfields you will be able to solve this problem pretty easily.
You can do one thing give tag to all textfields and check whether string you entered in current textfield is same as text of all other textfields then return NO.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
// These are the characters that are ~not~ acceptable
NSCharacterSet *unacceptedInput = [[NSCharacterSet characterSetWithCharactersInString:CHARACTERS] invertedSet];
NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
if (([[string componentsSeparatedByCharactersInSet:unacceptedInput] count] >1 ) | ([newString length] > 1) )
return NO;
else
//Call function to check if string is same as other textfield.text then return NO else YES
}
else
another option is you can take 1 string and save textfield.text in that string and update all time when you enter and check with it whether the string you are entering is in substring of that string.
best of luck
At the time of creating UITextField set the keyboardType as UIKeyboardTypeNumberPad.
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if([[textField text]length]==1)
//perform condition
else
//perform condition
}
this might help
精彩评论