How to restrict UIalertview in this code? - ios

I have created a US-format mobile number. This code does not display letters and special characters. It successfully displays but it displays UIAlertviews, when the user enters letters and special characters in UITextfield, it shows some UIAlertview. How can I control the UIAlertviews? I want to display only one Alertview.
This is the code that I already have:
if(textField==mobileNo)
{
NSCharacterSet *myCharSet = [NSCharacterSet characterSetWithCharactersInString:#"0123456789"];
for (int i = 0; i < [string length]; i--) {
unichar c = [string characterAtIndex:i];
if (![myCharSet characterIsMember:c]) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Alphbets and Special characters not allowed" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
return NO;
}
}
}

You could try the following... but its not a great solution.....
In your header declare a BOOL to check if the alert view has been shown already, like so:
BOOL alertCheck;
In your viewDidLoad set it to NO:
alertCheck = NO;
Then in your code, check it before deciding to display your alertview.
if(textField==mobileNo) {
NSCharacterSet *myCharSet = [NSCharacterSet characterSetWithCharactersInString:#"0123456789"];
for (int i = 0; i < [string length]; i--) {
unichar c = [string characterAtIndex:i];
if (![myCharSet characterIsMember:c]) {
if (alertCheck == NO) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Alphbets and Special characters not allowed" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
alertCheck = YES;
}
return NO;
}
}
}

You can try the following:
if (![myCharSet characterIsMember:c]) {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
//show the UIAlertView
});
}

That code isn't so nice. You're just checking if the string value is a number or not. To do that you can use [NSScanner scannerWithString:] this way:
bool isNumber = [[NSScanner scannerWithString: string] scanInt:nil]
if (!isNumber) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Alphbets and Special characters not allowed" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
}
Code seems to be clearer and a lot more simpler.
Hope it helped!

Related

UITextView not picking up text input iOS

i have UITextView and i want to show a alert if empty
.h
#property (nonatomic, strong) IBOutlet UITextView *textField;
.m
- (IBAction)next:(id)sender {
if ([self.textField.text length] == 0) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error!"
message:#"text empty"
delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
}
}
alert is not showing and i can move on without any text being inputted. can anyone help me figure out why?
thanks
I checked this from my end and its working perfectly.
Here is download link for testing the project
I am sure, textview is not connected to IB.
If its is connected to IB, then I would say to upload sample project on dropbox to check from our end.
There is a possibility of the textField having whitespace characters. Try trimming out any possible whitespace using the following:
NSString *text = [self.textField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet];
if ([text length] == 0) {
....
}
Try this -
- (IBAction)next:(id)sender {
NSCharacterSet *whitespace = [NSCharacterSet whitespaceAndNewlineCharacterSet];
NSString *trimmed = [self.textField.text stringByTrimmingCharactersInSet:whitespace];
if ([trimmed length] == 0) {
// Text was empty or only whitespace.
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error!"
message:#"text empty"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
}
}

Check if UITextfield contains (? ! $ , etc)

Im doing a conditional statement that checks if a textfield contains certain characters, if it does they an UIAlertView will show. At the moment if the text field contains letters then an the alert is shown, how would I extend my method below to include characters such as ? ! , $ etc.
if ([self.withdrawTextField.text rangeOfCharacterFromSet:[NSCharacterSet letterCharacterSet]].location != NSNotFound) {
UIAlertView * alert = [[UIAlertView alloc] initWithTitle:#"Ooops" message:#"Please only use numbers and the period (.)." delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
}
Try this:
NSMutableCharacterSet *mcs1 = [[NSCharacterSet letterCharacterSet] mutableCopy];
[mcs1 addCharactersInString:#"?!.$"];
if ([self.withdrawTextField.text rangeOfCharacterFromSet:mcs1].location != NSNotFound) {
UIAlertView * alert = [[UIAlertView alloc] initWithTitle:#"Ooops" message:#"Please only use numbers and the period (.)." delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
}
As you want only numbers and dot in the string than you can try below code. It may help you.
NSCharacterSet *myCharSet = [NSCharacterSet characterSetWithCharactersInString:#"0123456789."];
for (int i = 0; i < [[self.withdrawTextField.text length]; i++)
{
unichar c = [string characterAtIndex:i];
if (![myCharSet characterIsMember:c])
{
UIAlertView * alert = [[UIAlertView alloc] initWithTitle:#"Ooops" message:#"Please only use numbers and the period (.)." delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
return;
}
}

validate multi uitextfield

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;
}

How do I make an alert show how long it took to complete a certain amount of questions in xcode?

I want to show the user how long it took him or her to answer a certain amount of questions (for example 5) as an alert. I believe that I have the correct timer in place although I could be wrong. How would I finish the coding?
- (void)updateCounter:(NSTimer *)theTimer {
static int count = 0;
count += 1;
NSString *s = [[NSString alloc]
initWithFormat:#"%d", count];
self.timer.text = s;
[s release];
}
- (void)generate
{
int a = 1 + arc4random() % 12;
int b = 1 + arc4random() % 12;
int sum = a * b;
label.text = [NSString stringWithFormat: #"%d * %d = ", a, b];
label.tag = sum;
}
- (void)viewDidLoad
{NSLog(#"viewDidLoad");
[super viewDidLoad];
[self generate];
[self.answer becomeFirstResponder];
UIAlertView *alert;
{alert = [[UIAlertView alloc]
initWithTitle:#"Welcome to iCanMultiply!"
message:#"Tap 'Start' to start the game"
delegate: self
cancelButtonTitle:#"Start"
otherButtonTitles: nil];
}
[alert show];
[alert release];
[NSTimer scheduledTimerWithTimeInterval:1.0f
target:self
selector:#selector(updateCounter:)
userInfo:nil
repeats:YES];
}
- (IBAction)submit:(id)sender {
int num = [answer.text intValue];
UIAlertView *alert;
if (num == label.tag)
{
// answer was correct
alert = [[UIAlertView alloc]
initWithTitle:#"Correct"
message:#"Bet you can't do that twice!"
delegate:self
cancelButtonTitle:#"Next Question"
otherButtonTitles: nil];
// use the alert tag to mark that answer was correct
alert.tag = 1;
} else
{
// answer is incorrect
alert = [[UIAlertView alloc]
initWithTitle:#"Wrong!"
message:#"Sorry, try again..."
delegate:self
cancelButtonTitle:#"Try Again"
otherButtonTitles: nil];
}
// show and release the alert
[alert show];
[alert release];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (alertView.tag == 1)
{
[self generate];
answer.text = #"";
}
}
Store that value and then display it in an alert view.
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Title" message#"It took you %# seconds.",time delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
Let me know if the ,time works. I haven't tested this yet, but it should work.

iphone response [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
i am getting response like {"nok"} .... now i want to compare this for check status of data sent or not.
this is my code
NSString *responseStr = [sender responseString];
NSLog(#"response string %#", responseStr);
if([responseStr isEqualToString:#"nok"])
{
NSLog(#"Hiii");
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"" message:#"Attenzione: si è verificato un errore di richiesta del premio." delegate:self cancelButtonTitle:nil otherButtonTitles:#"OK", nil];
[alert show];
[alert release];
}
else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"" message:#"Inviato con successo" delegate:self cancelButtonTitle:nil otherButtonTitles:#"OK", nil];
[alert show];
[alert release];
[self startIscrivity2View];
}
it's always run else part...
please help me
USe the below function of NSString.
- (NSRange)rangeOfString:(NSString *)aString
The above function will not check for the equality, it will tell u whether your responseStr contain "nok" string OR not ..
NSRange myStringRange = [responseStr rangeOfString:#"nok"] ;
if(myStringRange.location != NSNotFound )
{
NSLog(#"Hiii");
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"" message:#"Attenzione: si è v erificato un errore di richiesta del premio." delegate:self cancelButtonTitle:nil otherButtonTitles:#"OK", nil];
[alert show];
[alert release];
}
else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"" message:#"Inviato con successo" delegate:self cancelButtonTitle:nil otherButtonTitles:#"OK", nil];
[alert show];
[alert release];
[self startIscrivity2View];
}
}
Try:
if([responseStr isEqualToString: #"nok"])
{
...
}
Try replacing
responseStr == #"nok"
with
[responseStr isEqualToString:#"nok"];
In your code, the variable is not checking if the characters in the string are the same, it is checking if they are pointing to the same location in memory.
Try isEqualToString
if([responseStr isEqualToString:#"nok"]){
}
or compare
if([responseStr compare:#"nok"] == NSOrderedSame){
}
Never compare 2 strings using == operator.
Try.
if([responseStr isEqualToString: #"{\"nok\"}"] == TRUE)
{
....
}
else
{
.....
}
Or you can remove all exara characters from response string and then compair it.
Like -
NSString *str = [responseStr stringByReplacingOccurrencesOfString:#"{" withString:responseStr];
str = [responseStr stringByReplacingOccurrencesOfString:#"}" withString:responseStr];
str = [responseStr stringByReplacingOccurrencesOfString:#"\"" withString:responseStr];
if([responseStr isEqualToString: #"nok"] == TRUE)
{
....
}
else
{
.....
}
Or you can try.
NSRange myStringRange = [responseStr rangeOfString:#"nok"] ;
if(myStringRange.location != NSNotFound )
{
...
}
else
{
...
}

Resources