I use this code to check if text fields are empty or not. The first time, it will work, but when I change the text field values, the alert does not works.
-(void)sendclick {
NSString *msg;
if(firstnametextfield.text==NULL) {
msg=#"enter first name";
NSLog(#"%#",firstnametextfield.text);
}
else if(lastnametextfield.text==NULL) {
msg=#"enter last name";
NSLog(#"%#",lastnametextfield.text);
}
else if(emailtextfield.text==NULL) {
msg=#"enter email address";
NSLog(#"%#",emailtextfield.text);
}
else if(companytextfield.text==NULL) {
msg=#"enter company name";
NSLog(#"%#",companytextfield.text);
}
else if(phonetextfield.text==NULL) {
msg=#"enter phone numper";
NSLog(#"%#",phonetextfield.text);
}
else {
msg=#"register success fully";
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error" message:msg delegate:self cancelButtonTitle:nil otherButtonTitles:#"OK", nil];
[alert show];
[alert release];
}
}
There are a couple of things to consider about this code:
As others have pointed out, this is not the correct way to check for an empty string.
a. First, if you do want to check for a string that is not allocated, you should be checking for nil and not NULL.
b. Secondly, the string could also be allocated, but have no characters, so you should check to see if it is an empty string as well.
c. Note that you typically want to check BOTH of those conditions, and do the same thing, because, usually, there is no difference between a string that is nil and one that is empty as far as the business logic is concerned.
d. The easiest way to do this is to simply check the length of the string. This works, because if a message is sent to a nil object, it will return 0, and if it is an actual string with no characters, it will also return 0.
Therefore, a check similar to this would work instead:
if([firstnametextfield.text length] == 0)
You typically do not want to check the value of a text field directly like this for form validation. This is because, under certain situations (like when a text field is in a table view cell and scrolls off of the screen) the text field is not available and you won't have access to the data stored in the text field.
Instead, you should collect the text immediately after it is entered by setting the delegate of the text field to your view controller and implementing the following function:
- (void)textFieldDidEndEditing:(UITextField *)textField {
if (textField == firstnametextfield) {
// Store the first name in a property, or array, or something.
}
}
Then, when you are ready to validate the entered information, check the values that you have stored instead of the actual text field values themselves, using the technique from #1 above.
You shouldn't compare the text field value with NULL. Rather, compare it with #"". You can also trim whitespace characters too:
[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
- (BOOL)isEmptyOrNull:(NSString*)string {
if (string) {
if ([string isEqualToString:#""]) {
return YES;
}
return NO;
}
return YES;
}
-(void)sendclick {
NSString *msg;
if([self isEmptyOrNull:firstnametextfield.text]) {
msg=#"enter first name";
NSLog(#"%#",firstnametextfield.text);
}
.....
.....
.....
Try using
if([lastnameTextField.text isEqualToString:#""])
{
msg = #"Enter last name";
NSLog(#"%#",lastnametextfield.text);
}
This is how you check if a NSString is empty or not.
You can't compare string objects using the == or != operators. So here is the correct one:
-(void)sendclick
{
NSString *msg;
if([firstnametextfield.text isEqualToString:#""])
{
msg=#"enter first name";
NSLog(#"%#",firstnametextfield.text);
}
else
if([lastnametextfield.text isEqualToString:#""])
{
msg=#"enter last name";
NSLog(#"%#",lastnametextfield.text);
}
else if([emailtextfield.text isEqualToString:#""])
{
msg=#"enter email address";
NSLog(#"%#",emailtextfield.text);
}
else if([companytextfield.text isEqualToString:#""])
{
msg=#"enter company name";
NSLog(#"%#",companytextfield.text);
}
else if([phonetextfield.text isEqualToString:#""])
{
msg=#"enter phone numper";
NSLog(#"%#",phonetextfield.text);
}
else
{
msg=#"register success fully";
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error" message:msg delegate:self cancelButtonTitle:nil otherButtonTitles:#"OK", nil];
[alert show];
[alert release];
}
}
I hope that helps you.
-(void)sendclick
{
if ([self ControlValidation]==YES)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Sucess" message:#"Registration done successfully" delegate: nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
}
-(BOOL)ControlValidation
{
if ([self isEmpty:firstnametextfield.text ]==YES)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Sorry" message:#"First Name is empty" delegate: nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
return NO;
}
if ([self isEmpty:lasttnametextfield.text ]==YES)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Sorry" message:#"Last Name is empty" delegate: nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
return NO;
}
return YES;
}
-(BOOL)isEmpty:(NSString *)str
{
if (str == nil || str == (id)[NSNull null] || [[NSString stringWithFormat:#"%#",str] length] == 0 || [[[NSString stringWithFormat:#"%#",str] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length] == 0)
{
return YES;
}
return NO;
}
-(void)validateTextFields
{
if ([self Validation]==YES)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Sucess" message:#"Registration done successfully" delegate: nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
}
-(BOOL)Validation
{
if ([self isEmpty:firstnametextfield.text ]==YES)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Sorry" message:#"First Name is empty" delegate: nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
return NO;
}
if ([self isEmpty:lasttnametextfield.text ]==YES)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Sorry" message:#"Last Name is empty" delegate: nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
return NO;
}
if ([self isEmpty:Usernametextfield.text ]==YES)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Sorry" message:#"First Name is empty" delegate: nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
return NO;
}
if ([self isEmpty:phonetextfield.text ]==YES)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Sorry" message:#"Last Name is empty" delegate: nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
return NO;
if ([self isEmpty:emailtextfield.text ]==YES)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Sorry" message:#"First Name is empty" delegate: nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
return NO;
}
if ([self isEmpty:passwordtextfield.text ]==YES)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Sorry" message:#"Last Name is empty" delegate: nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
return NO;
}
}
return YES;
}
-(BOOL)isEmpty:(NSString *)str
{
if (str == nil || str == (id)[NSNull null] || [[NSString stringWithFormat:#"%#",str] length] == 0 || [[[NSString stringWithFormat:#"%#",str] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length] == 0)
{
return YES;
}
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
I have a sign-up view controller that contains multiple text fields to register the user.
I need to validate all the text fields such as not empty, valid email, username, password etc. and display the alert message for all different condition.
Now I following the approach as:
if (condition) {
if (condition) {
if (condition) {
} else {
[alert show];
}
} else {
[alert show];
}
} else {
[alert show];
}
I know this is not the best approach. So guys please suggest an appropriate way to do that task.
Thanks,
Multiple If else Condition
NSString *emailRegEx = #"[A-Z0-9a-z._%+-]+#[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
NSPredicate *emailTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", emailRegEx];
NSString *mobileRegex = #"[0-9]{6,14}$";
NSPredicate *mobileTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", mobileRegex]
if (txtName.text.length == 0)
{
[[[UIAlertView alloc]initWithTitle:#"Alert" message:#"Please Enter Name" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil] show];
}
else if (txtMobile.text.length == 0)
{
[[[UIAlertView alloc]initWithTitle:#"Alert" message:#"Please Enter Mobile Number" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil] show];
}
else if ([mobileTest evaluateWithObject:txtMobile.text] == NO)
{
[[[UIAlertView alloc]initWithTitle:#"Alert" message:#"Please Enter valid Mobile Number" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil] show];
}
else if (txtMobile.text.length < 10)
{
[[[UIAlertView alloc]initWithTitle:#"Alert" message:#"Please Enter valid Phone Number" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil] show];
}
else if (txtMobile.text.length > 10)
{
[[[UIAlertView alloc]initWithTitle:#"Alert" message:#"Please Enter valid Phone Number" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil] show];
}
else if (txtEmail.text.length == 0)
{
[[[UIAlertView alloc]initWithTitle:#"Alert" message:#"Please Enter Email" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil] show];
}
else if ([emailTest evaluateWithObject:txtEmail.text] == NO)
{
[[[UIAlertView alloc]initWithTitle:#"Alert" message:#"Please Enter valid Email" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil] show];
}
else
{
//success Code
}
Here isAllFieldsAreValid() will validate all the fields you can add all the validation here.
showAlert is a method to show alert about error.
allTrim() is a macro that will trim whitespace.
- (BOOL)isAllFieldsAreValid {
//here only empty string is checked you can add other if-else to validate email, phno, etc.
if ([allTrim(self.txtFname.text) isEqualToString:#""]) {
[self showAlert:#"Please enter first name."];
return false;
} else if ([allTrim(self.txtLname.text) isEqualToString:#""]) {
[self showAlert:#"Please enter last name."];
return false;
} else if ([allTrim(self.txtEmail_SignUp.text) isEqualToString:#""]) {
[self showAlert:#"Please enter email id."];
return false;
} else if ([allTrim(self.txtPassword_SignUp.text) isEqualToString:#""]) {
[self showAlert:#"Please enter password."];
return false;
}
return true;
}
You can call this on button click and upon true and false you can take action.
- (IBAction)buttonTappedInLoginView:(UIButton *)sender {
if ([self isAllFieldsAreValid]) {
// do stuff
}
}
Use this code,
if (firstnametf.text.length==0 || lastnametf.text.length==0 || emailtf.text.length==0 || myimageView.image == nil || commenttf.text.length==0 || [commenttf.text isEqualToString:#"Comment"])
{
[self validatetextfield];
}
else if (![emailtf.text isEqualToString:#""])
{
NSString *emailRegEx = #"[A-Z0-9a-z._%+-]+#[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
NSPredicate *emailTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", emailRegEx];
//Valid email address
if ([emailTest evaluateWithObject:emailtf.text] == YES)
{
//All conditions are checked, you will set the function
}
else if ()
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Test!" message:#"Please Enter Valid Email Address. \nex. fdsjfkd#mail.com" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
}
}
Method:
-(void) validatetextfield
{
if (firstnametf.text.length==0) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Firstname Field Empty!" message:#"Please Enter the Valid Details" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[firstnametf becomeFirstResponder];
}
else if (lastnametf.text.length==0)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Lastname Field Empty!" message:#"Please Enter the Valid Details" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[lastnametf becomeFirstResponder];
}
else if (emailtf.text.length==0)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Email Field Empty!" message:#"Please Enter the Valid Details" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[emailtf becomeFirstResponder];
}
else if(commenttf.text.length==0)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Comment Field Empty!" message:#"Please Enter the Valid Details" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[commenttf becomeFirstResponder];
}
else if ([commenttf.text isEqualToString:#"Comment"])
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Comment Field Empty!" message:#"Please Enter the Valid Details" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[commenttf becomeFirstResponder];
}
else if (myimageView.image == nil)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Image not Upload!" message:#"Please Upload Image" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
}
Change the Alert condition, hope its helpful
I'm writing a signup view controller for my app. I needed to validate the form. I got the idea that setting a selector method for text value change should work for different textfields containing the form data.
I saw old questions and stuff on google and this is what I have so far
- (void)viewDidLoad
{
[super viewDidLoad];
self.passwordInput.secureTextEntry = YES;
self.btnDone.enabled = NO; //Done button needs to be disabled until form is properly validated
self.emailInput.delegate = self; //emailinput is the property attached to Email textfield of the form
self.passwordInput.delegate = self;
emailCheck = NO;
passwordCheck = NO;
[self.emailInput addTarget:self action:#selector(formValidation) forControlEvents:UIControlEventValueChanged];
[self.passwordInput addTarget:self action:#selector(formValidation) forControlEvents:UIControlEventValueChanged];
// Do any additional setup after loading the view from its nib.
}
-(void) formValidation {
NSString *regex = #"[^#]+#[A-Za-z0-9.-]+\\.[A-Za-z]+";
NSPredicate *emailPredicate = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", regex];
if(self.passwordInput.text.length >7)
{
passwordCheck = YES;
}
if([emailPredicate evaluateWithObject:self.emailInput.text])
{
emailCheck = YES;
}
if (self.passwordInput.text.length<7 || ![emailPredicate evaluateWithObject:self.emailInput])
{
self.warningLabel.text = #"Please enter a valid email/at least 8 character password";
}
if(passwordCheck == YES && emailCheck ==YES)
{
self.btnDone.enabled = YES;//button is enabled
} }
Now the problem is that the event is not firing off. Nothing happens when enter the data. Can anyone guide me what I'm doing wrong here?
P.s. i don't quite understand UITextFieldTextDidChangeNotification. If someone can suggest an alternative solution or explain that concept for me, it'd be awesome
I just tried forControlEvents:UIControlEventEditingChanged, the app crashes with error that it can't perform regular expression.**"Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Can't do regex matching on object <UITextField: 0x9ae8610;"**
Set the delegate of textfields and use the following method
-(void)textFieldDidEndEditing:(UITextField *)textField
{
[self validateForm:textField.text];
}
and change form validator function to
-(void) validateForm:(NSString *)inputString {
//validate inputString
}
on button submit click of form even you can check validation like below.
- (IBAction)pushToSignConfirmationScreen:(id)sender;
{
NSString *emailString = txt_Email.text;// storing the entered email in a string.
/ / Regular expression to checl the email format.
NSString *emailReg = #"[A-Z0-9a-z._%+-]+#[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
NSPredicate *emailTest=[NSPredicate predicateWithFormat:#"SELF MATCHES %#", emailReg];
if ([txt_ContactName.text length] == 0 || [txt_Address.text length] == 0
|| [txt_DBAName.text length] == 0 || [txt_City.text length] == 0
|| [txt_Email.text length] == 0 || [txt_Phone.text length] == 0
|| [txt_State.text length] == 0)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Warning" message:#"All fields are required to begin setting up a merchant account." delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
return;
}
else if(([emailTest evaluateWithObject:emailString]!=YES)||[emailString isEqualToString:#""])
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Warning" message:#"Enter your email in abc#example.com format." delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
txt_Email.text = #"";
[btn_next setImage:[UIImage imageNamed:#"tag_icon_bt_up1.png"] forState:UIControlStateNormal];
return;
}
else if([txt_ZipCode.text length]!=5)
{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Warning" message:#"Please enter a valid zip code." delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
txt_ZipCode.text = #"";
return;
}
else if([txt_Phone.text length]!=10 )
{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Warning" message:#"Please enter a valid mobile number." delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
txt_Phone.text = #"";
return;
}
First set the delegate for textfield, then do check in Method:-
- (BOOL)textFieldShouldReturn:(UITextField *)textField.
If textField is same then call your formValidation method.
I have two buttons that will pop up an alertview with textfield to input data. However, only certain characters are allowed in each of the two textfields. Somehow, if I press the second button, the character set from the first button is used. What's going on here?
Also, what would be a more elegant form of inputting data without having to use an alertview? Could I use a modal view? If so, how?
- (IBAction)editRate
{
if(!self.powerOn) return;
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Edit Jail Fee Rate"
message:#"Enter New Daily Rate"
delegate:self
cancelButtonTitle:#"Cancel"
otherButtonTitles:#"Ok", nil];
alert.alertViewStyle = UIAlertViewStylePlainTextInput;
[[alert textFieldAtIndex:0] setKeyboardType:UIKeyboardTypeNumberPad];
[alert show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (buttonIndex != alertView.cancelButtonIndex)
{
UITextField *field = [alertView textFieldAtIndex:0];
field.placeholder = #"Enter New Rate";
NSCharacterSet * set = [[NSCharacterSet characterSetWithCharactersInString:#"0123456789."] invertedSet];
if ([field.text rangeOfCharacterFromSet:set].location != NSNotFound)
{
UIAlertView *errorAlert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Only numbers are allowed in this field."delegate:self cancelButtonTitle:#"OK"otherButtonTitles:nil];
[errorAlert show];
FeeRate.text=#"0.00";
}
else
{
FeeRate.text = field.text;
[[NSUserDefaults standardUserDefaults] setObject:field.text forKey:RATE_KEY];
[[NSUserDefaults standardUserDefaults] synchronize];
}
}
else
{
}
}
- (IBAction)editDate
{
if(!self.powerOn) return;
UIAlertView *alertDate = [[UIAlertView alloc] initWithTitle:#"Edit Jail Fee Date"
message:#"Enter New Date"
delegate:self
cancelButtonTitle:#"Cancel"
otherButtonTitles:#"Ok", nil];
alertDate.alertViewStyle = UIAlertViewStylePlainTextInput;
[[alertDate textFieldAtIndex:0] setKeyboardType:UIKeyboardTypeNumberPad];
[alertDate show];
}
- (void)alertDate:(UIAlertView *)alertDate clickedButtonAtIndex:(NSInteger)buttonIndex2
{
if (buttonIndex2 != alertDate.cancelButtonIndex)
{
UITextField *fieldDate = [alertDate textFieldAtIndex:0];
fieldDate.placeholder = #"Enter New Date";
NSCharacterSet * setnew = [[NSCharacterSet characterSetWithCharactersInString:#"0123456789/"] invertedSet];
if ([fieldDate.text rangeOfCharacterFromSet:setnew].location != NSNotFound)
{
UIAlertView *errorAlert1 = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Only numbers and slashes are allowed in this field."delegate:self cancelButtonTitle:#"OK"otherButtonTitles:nil];
[errorAlert1 show];
FeeDate.text=#"00/00/0000";
}
else
{
FeeDate.text = fieldDate.text;
[[NSUserDefaults standardUserDefaults] setObject:fieldDate.text forKey:DATE_KEY];
[[NSUserDefaults standardUserDefaults] synchronize];
}
}
else
{
}
}
When a UIAlertView is dismissed then a function called
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
is called.
So, both your alert views call this function.
One way to tell which alertView is calling it, you could create an ivar or better two properties like this:
#property (nonatomic, strong) UIAlertView *rateAlert;
#property (nonatomic, strong) UIAlertView *dateAlert;
and you should initialize like this:
[self setRateAlert:[[UIAlertView alloc] initWithTitle...
[self.rateAlert show];
and
[self setDateAlert:[[UIAlertView alloc] initWithTitle...
[self.dateAlert show];
and then:
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (alertView==self.rateAlert) {
//do whatever for rateAlert
} else {
//do whatever with dateAlert
}
}
I've written a simple app which validates user input (whether NULL or longer than a define length). It should return validation error messages when validation fails and otherwise, redirect to another page.
However, the app only returns the messge for the first condition (Username is Empty) for all scenarions. (Such as username is filled and password is empty, etc.)
m file:
- (IBAction)doLogin {
if(uname.text==NULL) {
UIAlertView *err1 = [[UIAlertView alloc]
initWithTitle:#"Required field!" message:#"Username is empty." delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[err1 show];
NSLog(#"%#",uname.text);
}
else if(passw.text==NULL) {
UIAlertView *err2 = [[UIAlertView alloc]
initWithTitle:#"Required field!" message:#"Password is empty." delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[err2 show];
NSLog(#"%#",passw.text);
}
else if (uname.text.length < 6)
{
UIAlertView *err3 = [[UIAlertView alloc]
initWithTitle:#"Invalid!" message:#"Enter a username longer than 6 chars." delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[err3 show];
NSLog(#"%#",uname.text);
}
else if (uname.text.length < 8)
{
UIAlertView *err4 = [[UIAlertView alloc]
initWithTitle:#"Invalid!" message:#"Enter a password longer than 8 chars." delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[err4 show];
NSLog(#"%#",uname.text);
}
else {
/*UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"" message:#"Thank you" delegate:self cancelButtonTitle:#"Close" otherButtonTitles:#"OK", nil];
[alert show];*/
UIViewController* flipViewController = [[UIViewController alloc] initWithNibName:#"flip" bundle:[NSBundle mainBundle]];
[self.view addSubview:flipViewController.view];
}
An alternative to karthika (but using similar structure) this will provide feedback on the entire form in a single message. Perhaps a little more user friendly and certainly reduces negative user interaction.
-(BOOL)isFormDataValid{
NSMutableArray *errorMessages = [[NSMutableArray alloc] init];
if([self.emailTextField.text isEqualToString:#""])
{
[errorMessages addObject:NSLocalizedString(#"Please enter email",nil)];
}
if([self.passwordTextField.text isEqualToString:#""])
{
[errorMessages addObject:NSLocalizedString(#"Please enter password",nil)];
}
if ([errorMessages count]) {
NSString * msgs = [errorMessages componentsJoinedByString:#"\n"];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(#"Whoops!",nil) message:msgs delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
return NO;
} else {
return YES;
}
}
-(BOOL)isFormDataValid{
NSString *errorMessage = nil;
UITextField *errorField;
if([nameTextField.text isEqualToString:#""])
{
errorMessage = #"Please enter username";
errorField = nameTextField;
}
else if([[nameTextField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]==0)
{
errorMessage = #"white spaces not allowed";
errorField = nameTextField;
}
else if([passwordTextField.text isEqualToString:#""])
{
errorMessage = #"Please enter password";
errorField = passwordTextField;
}
else if([[passwordTextField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]==0)
{
errorMessage = #"white spaces not allowed";
errorField = passwordTextField;
}
if (errorMessage) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Failed!" message:errorMessage delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
[errorField becomeFirstResponder];
return NO;
}else{
return YES;
}
}
Apart from the fact that you do
else if (uname.text.length < 8)
{
UIAlertView *err4 = [[UIAlertView alloc]
initWithTitle:#"Invalid!" message:#"Enter a password longer than 8 chars." delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[err4 show];
NSLog(#"%#",uname.text);
}
instead of
else if (passw.text.length < 8)
{
UIAlertView *err4 = [[UIAlertView alloc]
initWithTitle:#"Invalid!" message:#"Enter a password longer than 8 chars." delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[err4 show];
NSLog(#"%#",passw.text);
}
Your code should work just fine.
Also, bear in mind that a text field's text won't be nil, it will just be an empty string (lenght == 0), unless you explicitly set it to nil.
I have a button which I want to implement with password before triggering a segue if the password is correct. it all looks fine up to the moment when you type in wrong password and I have implemented another alertView to tell the user the password is wrong. When the alert view pops out and dismisses after some delay, it keeps re-appearing and disappearing and nothing else can be done on the screen!
How to stop the re appearing?
Below is my part of the code that deals with this:
- (IBAction)editLeagues:(id)sender {
[self presentAlertViewForPassword];
}
-(void)presentAlertViewForPassword
{
_passwordAlert = [[UIAlertView alloc]initWithTitle:#"Password"
message:#"Enter Password to edit Leagues"
delegate:self
cancelButtonTitle:#"Cancel"
otherButtonTitles:#"OK", nil];
[_passwordAlert setAlertViewStyle:UIAlertViewStyleSecureTextInput];
_passwordField = [_passwordAlert textFieldAtIndex:0];
_passwordField.delegate = self;
_passwordField.autocapitalizationType = UITextAutocapitalizationTypeWords;
_passwordField.tag = textFieldPassword;
[_passwordAlert show];
}
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
NSString *password = [NSString stringWithFormat:#"55555"];
if ( ![_passwordField.text isEqual:password]) {
_wrongPassword = [[UIAlertView alloc] initWithTitle:#"Wrong Password"
message:#"You are not authorised to use this feature!"
delegate:self
cancelButtonTitle:nil
otherButtonTitles:nil];
[_wrongPassword show];
[self performSelector:#selector(allertViewDelayedDissmiss:) withObject:nil afterDelay:2];
}
else
{
[self performSegueWithIdentifier:#"addLeague" sender:[alertView buttonTitleAtIndex:0]];
}
}
-(void) allertViewDelayedDissmiss:(UIAlertView *)alertView
{
[_wrongPassword dismissWithClickedButtonIndex:-1 animated:YES];
}
- (BOOL)alertViewShouldEnableFirstOtherButton:(UIAlertView *)alertView
{
NSString *inputText = [[alertView textFieldAtIndex:0] text];
if( [inputText length] >= 4 )
{
return YES;
}
else
{
return NO;
}
}
[_wrongPassword dismissWithClickedButtonIndex:-1 animated:YES]; will call the delegate method alertView:didDismissWithButtonIndex:
You have two options:
don't set a delegate on the wrong password alert
check for the correct alert in alertView:didDismissWithButtonIndex: e.g.
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
if (alert == _passwordAlert) {
NSString *password = [NSString stringWithFormat:#"55555"];
// and so on
}
}
Issue is causing because when you dismiss the wrong password alert it'll also call the didDismissWithButtonIndex delegate method.
Solution 1
Set the delegate of wrong password alert to nil.
wrongPassword = [[UIAlertView alloc] initWithTitle:#"Wrong Password"
message:#"You are not authorised to use this feature!"
delegate:nil
cancelButtonTitle:nil
otherButtonTitles:nil];
Solution 2
Add a tag to your alertView. And change your methods like:
-(void)presentAlertViewForPassword
{
_passwordAlert = [[UIAlertView alloc]initWithTitle:#"Password"
message:#"Enter Password to edit Leagues"
delegate:self
cancelButtonTitle:#"Cancel"
otherButtonTitles:#"OK", nil];
[_passwordAlert setAlertViewStyle:UIAlertViewStyleSecureTextInput];
passwordAlert.tag = 7;
_passwordField = [_passwordAlert textFieldAtIndex:0];
_passwordField.delegate = self;
_passwordField.autocapitalizationType = UITextAutocapitalizationTypeWords;
_passwordField.tag = textFieldPassword;
[_passwordAlert show];
}
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
if(alertView.tag == 7)
{
NSString *password = [NSString stringWithFormat:#"55555"];
if ( ![_passwordField.text isEqual:password])
{
_wrongPassword = [[UIAlertView alloc] initWithTitle:#"Wrong Password"
message:#"You are not authorised to use this feature!"
delegate:self
cancelButtonTitle:nil
otherButtonTitles:nil];
[_wrongPassword show];
[self performSelector:#selector(allertViewDelayedDissmiss:) withObject:nil afterDelay:2];
}
else
{
[self performSegueWithIdentifier:#"addLeague" sender:[alertView buttonTitleAtIndex:0]];
}
}
}