iPhone Text Field Validation


 

iPhone Text Field Validation

iPhone Text Field Validation - In any user based application "validations" plays a very important role in order to get unique and correct data from user.

iPhone Text Field Validation - In any user based application "validations" plays a very important role in order to get unique and correct data from user.

iPhone Text Field Validation

In any user based application "validations" plays a very important role in order to get unique and correct data from user. In this tutorial we are going to limiting the text field input length in iPhone app.

Let's find out what we are doing in the application...
Here we have created a view based application and called it "Validate". We have also take a Text field on the view to take the input from user.

Now we have to make sure that the max string length of the text field should be 6. That means user anyhow user should not be able to enter the data that have the string length more then 6.

To do that.. first we need to declare UITextFieldDelegate in .h file and then declare textValue.delegate = self; into viewDidLoad method, in the .m file

After that just create a method BOOL as given below...

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
    return !([newString length] > 6);
}

It'll validate the text field and it'll not accept more than 6 characters.

See the code below: validateViewController.h

#import <UIKit/UIKit.h>

@interface validateViewController : UIViewController < UITextFieldDelegate > {
    IBOutlet UITextField *textValue;
}
@property (nonatomic retain) IBOutlet UITextField *textValue;

@end

validateViewController.m

#import "validateViewController.h"

@implementation validateViewController
@synthesize textValue;

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

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
   
    // Release any cached data, images, etc that aren't in use.
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
    return !([newString length] > 6);
}

-(void)touchesBegan :(NSSet *)touches withEvent:(UIEvent *)event
{
    [textValue resignFirstResponder];
    [super touchesBegan:touches withEvent:event];
}

- (void)viewDidUnload {
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)dealloc {
    [super dealloc];
}

@end

You can also Download the iPhone Text Field Validation code.

 

Ads