-1

Hi i am beginner in Ios and in my project login page there is textfields validations(here i have two textfields they are medicaId,password)

my medicaid must allows only numbers and medicaId starts with 10 and ends with 99 if not then i want show alert Invalid medicaId

but according to my experience i could able to do only textfield allows numbers but i am not understand how to do that textfield(my medicaid) starts with 10 and ends with 99 please help me some one

my code:-

#import "ViewController.h"

@interface ViewController ()

#define ACCEPTABLE_CHARECTERS @"0123456789"

@end

@implementation ViewController

@synthesize textfield;

- (void)viewDidLoad {
    [super viewDidLoad];
    textfield.delegate = self;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string  {

    if (textField==textfield)
    {
        NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:ACCEPTABLE_CHARECTERS] invertedSet];

        NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];

        return [string isEqualToString:filtered];
    }
    return YES;
}

-(IBAction)CickMe:(id)sender{

    if (success) {

        NSLog(@"validations are perfect");
    }else{

        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Alert" message:@"MedicaId must starts with 10 and ends with 99" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:@"Cancel", nil];
        [alert show];
    }

}
AbhiRam
  • 2,033
  • 7
  • 41
  • 94

4 Answers4

1

My answer works perfectly.

- (IBAction)ClickMe:(id)sender
{
  NSString *strID = textFieldUserID.text;
  NSString *strLastTwoIndex = [strID substringFromIndex: [strID length] - 2];
  NSLog(@"The strJoinedStr is - %@",strLastTwoIndex);
  if([strID hasPrefix:@"10"] && [strLastTwoIndex isEqualToString:@"99"])
  {
    NSLog(@"Success");

  }
  else{
    NSLog(@"Failure");
  }
}

The console output is

Success
user3182143
  • 9,459
  • 3
  • 32
  • 39
0

You can take string from text field and check using set operation that if it contains only number or not.

Then use the NSString function like hasPrefix and hasSuffix to check, if it has certain value at start or end.

-(void) validate
{
    BOOL isSuccess = FALSE;
    NSString *input = textField.text;
    if(input.length > 4)
    {
        if([input hasPrefix:@"10"] && [input hasSuffix:@"99"])
            isSuccess = TRUE;
    }        
}
Apurv
  • 17,116
  • 8
  • 51
  • 67
0

In general these kind of constraints can easily be solved using regular expressions. They allow you to easily specify quite complex constraints on a given input string. (as long as you do not want to count). Take a look here for how to use regular expressions in Objective-C.

BUT you have a slightly different situation here that you have to deal with: the user is not going to input the entire string at once - he will input character after character. It is pretty much impossible to check during the user input wether or not what he is going to end up with might be a valid input. For example there will not be a leading 99 when the user types in the first few chars. You can certainly prevent him from typing in anything else other than numbers since they will ne never be a valid character anywhere in the entire input.

If you implement the entire validation inside shouldChangeCharactersInRange you are going to have a bad day:

Imagine the user starts typing

1 - does not start with 10 and does not end with 99 -> reject
10 - does not end with 99 -> reject
102 - does not end with 99 -> reject
1029 - does not end with 99 -> reject
10299 - approve
1299 - does no longer start with 10 -> reject

If you actually reject invalid input the user would never be able to get to a valid input since the starting point always will be invalid.

All you can do is perform a check and notify the user that the input is invalid - but you must not reject the input. (You can display an exclamation mark, change the font color, etc.)

As @Apurv wrote, in your "simple" situation you would probably not even need to use a regular expression but could use basic string operations. But the above statements regarding not rejecting the user input during the input remains true.

A slight variation of the strict statement above is that you can actually reject any non-number character since they will always create an invalid input.

Community
  • 1
  • 1
luk2302
  • 55,258
  • 23
  • 97
  • 137
0

Instead of dealing with hand-made methods you should really use Cocoa's core technologies.

A. Number Formatters

You should read the introduction to number formatters. Instances of NSNumberFormatter support a range with minimum and maximum values. Moreover, they transform strings to numbers and back.

B. Key-Value-Validation

The intended concept for value validation is key-value validation. You should alway implement this instead of custom-made methods. (I. e. you get the benefit, that technologies in Cocoa uses this methods, when doing its own validation.)

After allowing only numbers, you only have to filter out illegal values. In your case it would be:

-(BOOL)validateYourPropertyNameHere:(id *)ioValue error:(NSError * __autoreleasing *)outError {
  // Do some checking, i. e. …

}

Typed in Safari.

It is a littlebit tricky, because you have three options:

  • The value is correct: Simply return YES.
  • The value is incorrect, but can be converted to a correct value (i. e. input is 103 and you want to convert it to 99): create a new object and assign the reference to ioValue, return YES.
  • The value is incorrect and you cannot or don't want to convert it to a correct value: return NO.

C. Using

You use your validation method from everywhere you deal with the take-over of the input. simply:

NSError *error;
if( [self validateYourPropertyNameHere:&userInput error:&error] == NO )
{
  // Display error or whatever
}
else 
{
  // Use value
}

Don't hesitate to add comments, if you have more questions.

BTW:

#define ACCEPTABLE_CHARECTERS @"0123456789."
#define MAX_LENGTH 5

… is really no good style. But this is another Q. Maybe you should have a look at least at NSCharacterSet.

Amin Negm-Awad
  • 16,582
  • 3
  • 35
  • 50