iOS TextField Validation - iphone

I need a way to ensure that phone numbers have 10 digits with no other characters ie () - and make sure that email addresses are valid emails (formatted correctly).
Is there any library that can't make this easy for me so I don't have to write regular expressions.

This will check a UITextField for a proper email and phone number of 10 digits or less.
Add this method to the textFields delegate then check if the characters it is about to change should be added or not.
Return YES or NO depending on the text field, how many characters are currently in it, and what characters it wants to add:
#define ALPHA #"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
#define NUMERIC #"1234567890"
#define ALPHA_NUMERIC ALPHA NUMERIC
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSCharacterSet *unacceptedInput = nil;
switch (textField.tag) {
// Assuming EMAIL_TextField.tag == 1001
case 1001:
if ([[textField.text componentsSeparatedByString:#"#"] count] > 1)
unacceptedInput = [[NSCharacterSet characterSetWithCharactersInString:[ALPHA_NUMERIC stringByAppendingString:#".-"]] invertedSet];
else
unacceptedInput = [[NSCharacterSet characterSetWithCharactersInString:[ALPHA_NUMERIC stringByAppendingString:#".!#$%&'*+-/=?^_`{|}~#"]] invertedSet];
break;
// Assuming PHONE_textField.tag == 1002
case 1002:
if (textField.text.length + string.length > 10) {
return NO;
}
unacceptedInput = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
break;
default:
unacceptedInput = [[NSCharacterSet illegalCharacterSet] invertedSet];
break;
}
return ([[string componentsSeparatedByCharactersInSet:unacceptedInput] count] <= 1);
}
Also, check out these 2 articles:
Auto-formatting phone number UITextField on the iPhone
PhoneNumberFormatter.

Here's a simple way of ensuring phonenumber length in the UIViewController that has the text field in it's view.
- (void)valueChanged:(id)sender
{
if ([[[self phoneNumberField] text] length] > 10) {
[[self phoneNumberField] setText:[[[self phoneNumberField] text]
substringToIndex:10]];
}
}
- (void) viewWillAppear:(BOOL)animated
{
[[self phoneNumberField] addTarget:self
action:#selector(valueChanged:)
forControlEvents:UIControlEventEditingChanged];
}
For emails I suppose you want to check against a regexp when it loses focus.

Here's Simple Example for UITextField Validation while type in keyboard other characters not displaying
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
//UITextField *tf_phonenumber,*tf_userid;
if (textField.text<=10) {
char c=*[string UTF8String];
if (tf_phonenumber==textField) //PhoneNumber /Mobile Number
{
if ((c>='0' && c<='9')||(c==nil)) {
return YES;
}
else
return NO;
}
if (tf_userid==textField) //UserID validation
{
if ((c>='a' && c<='z')||(c>='A' && c<='Z')||(c==' ')||(c==nil)) {
return YES;
}
else
return NO;
}
return YES;
}
else{
return NO;
}
}

Related

Limiting the user to enter the characters and also to convert the each entered letter into capital letter in ios

I am having 4 text fields in which I want to put two limitations simultaneously. One is that the user should be able to type in only capital letters with the maximum character limit to 2 only. My code for this is as follows:-
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range
replacementString:(NSString *)string {
// Below logic is for All 4 Modifer Textfields
// we are restrict the user to enter only max 2 characters in modifier textfields.
if (textField==txt_modifier1 || textField==txt_modifier2 || textField==txt_modifier3 ||
textField==txt_modifier4) {
textField.text = [textField.text stringByReplacingCharactersInRange:range
withString:[string
uppercaseStringWithLocale:[NSLocale currentLocale]]];
NSUInteger newLength = [textField.text length] + [string length] - range.length;
return (newLength > 2) ? NO : YES;
}
return YES;
}
this is not functioning properly as it is appending one more character as I type in any character and also not limiting the number of characters to 2. Please suggest a way to tackle this problem.
You're manually updating the text in your textfield and then sending YES back (which then appends the characters a second time). Then, you're usingthe new text with the replacement string to compare it to two (which, then appends your characters again) ...
Try this:
if (...) {
NSString *result = [textField.text stringByReplacingCharactersInRange:range
withString:string.uppercaseString];
if (result.length <= 2)
textField.text = result;
return NO;
}
return YES;
For limiting the number of characters and capitalizing it in your UITextField, use this code block
-(BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
textField.text = [textField.text capitalizedString];
if(textField.text.length >= 3 && range.length == 0)
{
return NO;
}
else
{
return YES;
}
Please try to use this one ...It may help you
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if([string isEqualToString:[string capitalizedString]])
{
NSString *result = [textField.text stringByReplacingCharactersInRange:range
withString:string.uppercaseString];
if (result.length <= 2)
textField.text = result;
return NO;
}
else
return YES;
}
loginUITextFieldTextDidChangeNotificationMake judgment here
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(textChanged:)
name:UITextFieldTextDidChangeNotification
object:YOUR_TEXT_FIELD];
-(void)textChanged:(NSNotification *)notif {
//to do your logic
}

How to Append a Special Character after every 3 characters in UITextField Ex: (123-12346) like '-' i did it but issue while Clear

I am getting Phone card number form user in UI text field. The format of number is like
123-4567-890
I want that as user types 123 automatically - is inserted in UITextField same after 4567 - and so on.
I Did it using following code in UITextField delegate method:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string;
{
NSLog(#"***** %d",textField.text.length);
if(textField.text.length == 3)
{
textField.text = [textField.text stringByAppendingString:#"-"];
}
return YES;
}
But the Problem raised while clear the text, When we start clearing.
Last 3 digits 890 clears and then - addded, we cleared it and again added and soooo on so clearing stop at
We clear all the text at a time using
textField.clearButtonMode = UITextFieldViewModeWhileEditing; //To clear all text at a time
But our requirement is user must delete one character at a time.
How to achieve it?
During clearing replacementString should be empty #"". So replacement string should be checked also in addition to length check. Like this:
if (textField.text.length == 3 && ![string isEqualToString:#""]) {
// append -
}
USE: I have seen this somewhere in this forum, It worked for me
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSString *filter = #"###-####-###";
if(!filter) return YES;
NSString *changedString = [textField.text stringByReplacingCharactersInRange:range withString:string];
if(range.length == 1 && string.length < range.length && [[textField.text substringWithRange:range] rangeOfCharacterFromSet:[NSCharacterSet characterSetWithCharactersInString:#"0123456789"]].location == NSNotFound)
{
NSInteger location = changedString.length-1;
if(location > 0)
{
for(; location > 0; location--)
{
if(isdigit([changedString characterAtIndex:location]))
break;
}
changedString = [changedString substringToIndex:location];
}
}
textField.text = filteredStringFromStringWithFilter(changedString, filter);
return NO;
}
NSString *filteredStringFromStringWithFilter(NSString *string, NSString *filter)
{
NSUInteger onOriginal = 0, onFilter = 0, onOutput = 0;
char outputString[([filter length])];
BOOL done = NO;
while(onFilter < [filter length] && !done)
{
char filterChar = [filter characterAtIndex:onFilter];
char originalChar = onOriginal >= string.length ? '\0' : [string characterAtIndex:onOriginal];
switch (filterChar) {
case '#':
if(originalChar=='\0')
{
done = YES;
break;
}
if(isdigit(originalChar))
{
outputString[onOutput] = originalChar;
onOriginal++;
onFilter++;
onOutput++;
}
else
{
onOriginal++;
}
break;
default:
outputString[onOutput] = filterChar;
onOutput++;
onFilter++;
if(originalChar == filterChar)
onOriginal++;
break;
}
}
outputString[onOutput] = '\0';
return [NSString stringWithUTF8String:outputString];
}

Decimal style improvement objective c calculator

I'm doing the calculator tutorial for iOS and I've done some research for doing the decimal style. So far on my research, I've gone through this code below
- (IBAction)digitPressed:(UIButton *)sender {
NSString *digit = sender.currentTitle;
NSString *decimal = #".";
BOOL decimalAlreadyEntered = [self.display.text rangeOfString:decimal].location == NSNotFound ? NO : YES;
if (self.userIsInTheMiddleOfEnteringANumber) {
if (([digit isEqual:decimal] && !decimalAlreadyEntered) || !([digit isEqual:decimal])) {
[self.display setText:[[self.display text] stringByAppendingString:digit]];
}
}
else if ([self.display.text isEqual:#"0"] && digit == decimal){
[self.display setText:[[self.display text] stringByAppendingString:digit]];
self.userIsInTheMiddleOfEnteringANumber = YES;
}
else {
[self.display setText:digit];
self.userIsInTheMiddleOfEnteringANumber = YES;
}
}
This code helped me to prevent multiple decimal points being pressed by the user, and limit it only to one (as in 2.09). Cool! However during the start of the app, when I press on the decimal point and pressed on a number, say 1, the label will only display ( .1) instead of (0.1) . Any help for the improvement is much appreciated :)
In - (BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string you can check whether first value is "." then replace text value by "0.", whatever user has entered.And perform this check only when textfield value is ".something".
- (BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSString *symbol = [[NSLocale currentLocale] objectForKey:NSLocaleDecimalSeparator];
if (range.location == 0 && [string isEqualToString:symbol]) {
// decimalseparator is first
textField.text = [NSString stringWithFormat:#"0%#",textField.text];
return YES;
}
}

UITextField: backspace not working

I have an issue with UITextField's validation. I want to validate the UITextField's text-length to be 5(fixed).
my code :
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if(textField==codeTxt)
{
NSCharacterSet *unacceptedInput = [[NSCharacterSet characterSetWithCharactersInString:NUMBERS]invertedSet] ;
if ([[string componentsSeparatedByCharactersInSet:unacceptedInput] count] > 1)
return NO;
else if ([codeTxt.text length] >= 5])
return NO;
else
return YES;
}
}
this code works fine. It validates and ignores rest of the text(more thn 5).
my problem :
When I press Delete(Backspace), nothing happens !!! the text remains the same. delete(Backspace) does not work.
what could be the problem ?
Thanks...
put this condition at first statement in shouldChangeCharactersInRange method
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if([string length]==0)
{
return YES;
}
if(textField==codeTxt)
{
NSCharacterSet *unacceptedInput = [[NSCharacterSet characterSetWithCharactersInString:NUMBERS]invertedSet] ;
if ([[string componentsSeparatedByCharactersInSet:unacceptedInput] count] > 1)
return NO;
else if ([codeTxt.text length] >= 5])
return NO;
else
return YES;
}
}
Your only checking the length of the current text in the field. This method gets called before the text changes, so you need to check the replacementString's length first, then check the textField's text length.
Try this:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if (textField == codeTxt) {
// NSCharacterSet *unacceptedInput = [[NSCharacterSet characterSetWithCharactersInString:NUMBERS] invertedSet];
// if ([[string componentsSeparatedByCharactersInSet:[unacceptedInput count]] > 1) {
if ([[string componentsSeparatedByCharactersInSet:[[[NSCharacterSet characterSetWithCharactersInString:NUMBERS] invertedSet] autorelease]] count] > 1) {
return NO;
} else if ([string length] < 5) {
return YES;
} else if ([codeTxt.text length] >= 5]) {
return NO;
} else {
return YES;
}
}
}
Edit:
Checking the textField's length probably isn't even necessary after doing [codeTxt.text length] >= 5] since this will prevent the textField's length from ever going above 4 anyway.
Actually, you would need to check it since the default is to return YES;.
Probably needs to be <= 5
} else if ([string length] <= 5) {
return YES;
}
Instead of < 5 too
} else if ([string length] < 5) {
return YES;
}
I got the solution
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if(textField==codeTxt)
{
NSCharacterSet *unacceptedInput = [[NSCharacterSet characterSetWithCharactersInString:NUMBERS]invertedSet] ;
NSLog(#"textfield character validation method called");
NSLog(#"%d",[codeTxt.text length]);
if ([[string componentsSeparatedByCharactersInSet:unacceptedInput] count] > 1)
return NO;
else if ([codeTxt.text length] >= 5 && ![string isEqual:#""])
return NO;
else
return YES;
}
}

Validate against empty UITextField?

What is the value of a UITextField when it is empty? I can't seem to get this right.
I've tried (where `phraseBox' it the name of the said UITextField
if(phraseBox.text != #""){
and
if(phraseBox.text != nil){
What am I missing?
// Check to see if it's blank
if([phraseBox.text isEqualToString:#""]) {
// There's no text in the box.
}
// Check to see if it's NOT blank
if(![phraseBox.text isEqualToString:#""]) {
// There's text in the box.
}
found this at apple discussions when searching for the same thing,thought ill post it here too.
check the length of the string :
NSString *value = textField.text;
if([value length] == 0) {
}
or optionally trim whitespaces from it before validation,so user cannot enter spaces instead.works well for usernames.
NSString *value = [textField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
if([value length] == 0) {
// Alert the user they forgot something
}
Try following code
textField.text is a string value so we are checking it like this
if([txtPhraseBox.text isEqualToString:#""])
{
// There's no text in the box.
}
else
{
NSLog(#"Text Field Text == : %# ",txtPhraseBox.text);
}
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
NSString *fullText = [textField.text stringByAppendingString:string];
if ((range.location == 0) && [self isABackSpace:string]) {
//the textFiled will be empty
}
return YES;
}
-(BOOL)isABackSpace:(NSString*)string {
NSString* check =#"Check";
check = [check stringByAppendingString:string];
if ([check isEqualToString:#"Check"]) {
return YES;
}
return NO;
}
Use for text field validation:
-(BOOL)validation{
if ([emailtextfield.text length] <= 0) {
[UIAlertView showAlertViewWithTitle:AlertTitle message:AlertWhenemailblank];
return NO; }
return YES;}
Actually, I ran into slight problems using Raphael's approach with multiple text fields. Here's what I came up with:
if ((usernameTextField.text.length > 0) && (passwordTextField.text.length > 0)) {
loginButton.enabled = YES;
} else {
loginButton.enabled = NO;
}
Validation against empty UITextfield. if you don't want that UITextField should not accept blank white spaces. Use this code snippet:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSString *resultingString = [textField.text stringByReplacingCharactersInRange: range withString: string];
NSCharacterSet *whitespaceSet = [NSCharacterSet whitespaceCharacterSet];
if ([resultingString rangeOfCharacterFromSet:whitespaceSet].location == NSNotFound) {
return YES;
} else {
return NO;
}
}