Reputation: 335
I am trying to validate my text fields. I have two textfields Username and Password. I want to check that if the username textfield is kept empty then do not allow the user to move to the password textfield until he enters the username. Any sample code to do this will be much appreciated.
Thanks in advance.
Upvotes: 1
Views: 1811
Reputation: 12787
disable your password textField in viewDidLoad
yourPassWordTextField.enabled=NO;
and add a notification on textField by using
NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
[notificationCenter addObserver:self
selector:@selector (handle_TextFieldTextChanged:)
name:UITextFieldTextDidChangeNotification
object:self.yourUserIdTextField];
- (void) handle_TextFieldTextChanged:(id)notification {
if(![yourUserIdTextField.text isEqualToString:@""])
{
yourPassWordTextField.enabled=YES;
}
else
yourPassWordTextField.enabled=NO;
}
in .h file
-(void)registerForTextFieldNotifications;
declair this also.
Upvotes: 1
Reputation: 22305
Assuming you have some kind of submit button, I don't recommend trying to artificially keep the user in one field. Instead set the submitButton.enabled = NO
until both fields are valid. If you indicate that the fields are required then the user won't be nearly as confused as he would be if he couldn't change the text field focus.
For validation, in IB set both textfields' EditingChanged
pointing to a method in your viewContoller, something like ValidateEntry
. Give them both unique tags, just 1 and 2 or what have you.
In the ValidateEntry field determine which one is being edited -- the (id)sender will have a tag telling you which is which -- and when both fields are valid make the submit button available, submitButton.enabled = YES
. If either is invalid, disable it.
In my opinion this is much friendlier and results in exactly the same thing: no sending empty fields.
Upvotes: 2
Reputation: 1838
you make your username textfield as firstResponder.Then in Textfield did beginediting method check if characters entered or not.And in textfieldDidEndEditing,check if the textfield is not empty.If its not empty then allow password field to become first responder else keep first responder as username textfield itself.
Upvotes: 0
Reputation: 15115
You want to check this in – textFieldDidBeginEditing:
delegate
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
if(textField==passwordField)
{
if([userField.text isEqualToString:@""])
//Dont leave user field empty
}
}
Upvotes: 0