I have 4 text fields in my application.
I validate my textfields as textfield allow 0,1,...9 and .,for that i write code as fallows
- (IBAction) textfield:(id)sender {
if ([textfield.text length] > 0) {
if ([textfield.text length] > 10){
textfield.text = [textfield.text substringWithRange:NSMakeRange(0, 10)];
}
else {
//retrieve last character input from texfield
int I01 = [homevalue.text length];
int Char01 = [homevalue.text characterAtIndex:I01-1];
//check and accept input if last character is a number from 0 to 9
if ( (Char01 < 46) || (Char01 > 57) || (Char01 == 47) ) {
if (I01 == 1) {
textfield.text = nil;
}
else {
textfield.text = [homevalue.text substringWithRange:NSMakeRange(0, I01-1)];
}
}
}
}
}
It works fine, Now i need to validate that . allows only once with in the textfield.
eg: 123.45
According to my code if i place again . it is allowed.
eg:123.45.678
But it wont allowed once i place . ,that textfield wont allowed.
ed:123.45678.
How can i done this,
can any one pls help me.
Thank u in advance.
Try this predicate for texts that start with a number like "23.67"
NSString *decimalRegex = #"[0-9]+([.]([0-9]+)?)?"; // #"[0-9]+[.][0-9]+";
NSPredicate *decimalTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", decimalRegex];
BOOL isValidDecimal = [decimalTest evaluateWithObject:[textField text]];
If you want to allow "." at the fist place like ".95" use the following regex,
NSString *decimalRegex = #"[0-9]*([.]([0-9]+)?)?"; //#"[0-9]*[.][0-9]+";
Your code should look like this,
- (IBAction)textfield:(id)sender {
int textLength = [[textfield text] length];
if (textLength > 0) {
NSString *decimalRegex = #"[0-9]+([.]([0-9]+)?)?"; //#"[0-9]+[.][0-9]+";
NSPredicate *decimalTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", decimalRegex];
BOOL isValidDecimal = [decimalTest evaluateWithObject:[textField text]];
if (!isValidDecimal) {
NSString *text = [[textField text] substringToIndex:textLength - 1];
[textfield setText:text]
}
}
}
I guess this should work! Give it a try!
Well you can use this method
- (NSRange)rangeOfCharacterFromSet:(NSCharacterSet *)aSet options:(NSStringCompareOptions)mask range:(NSRange)aRange
on textfield.text as its a NSString only
Related
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];
}
I have a UITextField where in I am restricting entering more than 2 digits. Now, it works fine but when I tap on the text field & select all the content & then type it does not allow me to over-write the existing 2 digits.
Any clue on how to use 'selectedTextRange' property here?
- (BOOL)cell:(RunnerTableViewCell *)iCell shouldChangeCharactersInRange:(NSRange)iRange replacementString:(NSString *)iString {
self.navigationItem.rightBarButtonItem.enabled = YES;
NSCharacterSet *anUnacceptedInput = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
int aCharacterUpperLimit = 2;
BOOL aReturnValue = YES;
NSInteger aTotalLength = iCell.inputField.text.length + [iString length];
NSLog(#"iString=%# aTotalLength=%d",iString,aTotalLength);
if ([[iString componentsSeparatedByCharactersInSet:anUnacceptedInput] count] > 1 || (aTotalLength > aCharacterUpperLimit && ![iString isEqualToString:kRunnerEmptyString]) || [iString length] > aCharacterUpperLimit) {
aReturnValue = NO;
}
return aReturnValue;
}
Try this:
NSInteger aTotalLength = iCell.inputField.text.length + [iString length] - iRange.length;
I have an application where I have I a textfield where user enters his mobile number including his country code. The format of the mobile number to be entered is +91-9884715715. When the user enters his/her mobile number initially validation should be performed that the first value entered by user is '+' and then the number that is entered after + should not be less that 0.
But after this I am getting confused that how to get the number of numbers entered between + and -, because user enters the country code and the length of numbers entered between + and - must be dynamic not static.
Try this ., might help you
- (BOOL)textField:(UITextField *) textField shouldChangeCharactersInRange:(NSRange)range replacementString:
(NSString *)string {
NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
if (textField == self.yourphoneNumberfield) {
NSArray *sep = [newString componentsSeparatedByString:#"-"];
if([sep count] >= 2)
{
countryCode = [NSString stringWithFormat:#"%#",[sep objectAtIndex:0]];
if ([[countryCode substringToIndex:1] isEqualToString:#"+"]) {
phoneNumber = [NSString stringWithFormat:#"%#",[sep objectAtIndex:1]];
return ([countryCode length]+[phoneNumber length]);
}
}
}
return YES;
}
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField{
NSLog(#"Phone Number : %#",phoneNumber);
if (textField == self.yourphoneNumberfield) {
if ([phoneNumber length]<10)
{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"UIAlertView" message:#"Please Enter a Valid Mobile number" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
}
return YES;
}
Try This:
NSString *code=#"+91-99999999";
NSRange rr2 = [code rangeOfString:#"+"];
NSRange rr3 = [code rangeOfString:#"-"];
int lengt = rr3.location - rr2.location - rr2.length;
int location = rr2.location + rr2.length;
NSRange aa;
aa.location = location;
aa.length = lengt;
code = [code substringWithRange:aa];
NSLog(#"%#",code);
Goto XIB interface Builder and open xib document select ur phone number type textfield and go to textfield attribute, In the Text Input Traits, select Keyboard option from Default to Phone Pad.
// limit the input to only the stuff in this character set, so no emoji or any other insane characters
NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:#"1234567890"];
if ([string rangeOfCharacterFromSet:set].location == NSNotFound) {
return NO;
}
Refer #Bala's answer
NSString *call = #"+91-9884715715";
// Search for the "+a" starting at the end of string
NSRange range = [call rangeOfString:#"+" options:NSBackwardsSearch];
// What did we find
if (range.length > 0)
NSLog(#"Range is: %#", NSStringFromRange(range));
Edit
Refer following link: TextField Validation With Regular Expression
Change the line
- (BOOL)validateInputWithString:(NSString *)aString
{
NSString * const regularExpression = #"^([+]{1})([0-9]{2,6})([-]{1})([0-9]{10})$";
NSError *error = NULL;
Add the code
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
char *x = (char*)[string UTF8String];
//NSLog(#"char index is %i",x[0]);
if([string isEqualToString:#"-"] || [string isEqualToString:#"+"] || [string isEqualToString:#"0"] || [string isEqualToString:#"1"] || [string isEqualToString:#"2"] || [string isEqualToString:#"3"] || [string isEqualToString:#"4"] || [string isEqualToString:#"5"] || [string isEqualToString:#"6"] || [string isEqualToString:#"7"] || [string isEqualToString:#"8"] || [string isEqualToString:#"9"] || x[0]==0 ) {
NSUInteger newLength = [textField.text length] + [string length] - range.length;
return (newLength > 18) ? NO : YES;
} else {
return NO;
}
}
Edit
Tested with demo:
//// Button Press Event
-(IBAction)Check:(id)sender{
BOOL check = [self validateInputWithString:TextField.text];
if(check == YES){
NSLog(#"Hii");
NSString *string= [NSString stringWithFormat:#"%#", TextField.text];
NSArray *first = [string componentsSeparatedByString:#"-"];
NSString *second = [first objectAtIndex:1];
NSString *third = [first objectAtIndex:0];
if([second length] < 11){
NSLog(#"bang");
}
else{
NSLog(#"Fault");
}
if([third length] > 3 || [third length] < 7){
NSLog(#"Bang");
}
else{
NSLog(#"fault");
}
}
else{
NSLog(#"FAULT");
}
}
I need to remove all emoijs from a NSString.
So far i am using this NSString extension ...
- (NSString*)noEmoticon {
static NSMutableCharacterSet *emoij = NULL;
if (emoij == NULL) {
emoij = [[NSMutableCharacterSet alloc] init];
// unicode range of old emoijs
[emoij removeCharactersInRange:NSMakeRange(0xE000, 0xE537 - 0xE000)];
}
NSRange range = [self rangeOfCharacterFromSet:emoij];
if (range.length == 0) {
return self;
}
NSMutableString *cleanedString = [self mutableCopy];
while (range.length > 0) {
[cleanedString deleteCharactersInRange:range];
range = [cleanedString rangeOfCharacterFromSet:emoij];
}
return cleanedString;
}
... but that does not work at all. The range.length is always 0.
So the general question is : How can i remove a range of unicode characters from a NSString?
Thanks a lot.
It seems to me that in the above code the emoij variable is eventually an empty set. Didn't you mean to addCharactersInRange: rather than to removeCharactersInRange:?
I have been working on this for a few days now and I have some buzzy things going on with my textfields... and it's got to the point where I need to take a step back and hope someone with a fresh pair of eyes can shed light on the situation.
basically what I'm doing is formatting a 20 character string into sets of 5 as the user types after every 5th character a hyphen pops into the string, that works sweet.
I have a submit button that is not perusable until the 20th character is entered, this also works but where it gets CRAZY! is if you delete back one character the submit button still works.. then you delete back one more character and it doesn't work... I'm at a loss as my if statements conditions don't work like they should I specify == 23 characters and you have to hit one of the keys 24 times to get into that statement.. it makes no logical sense.
anyway if you could help me with the first question that would be great then if you have any ideas on the second question that would be great.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSString *separator = #"-";
int seperatorInterval = 5; //how many chars between each hyphen
NSString *originalString = [regTextField.text stringByReplacingOccurrencesOfString:separator withString:#""];
if (textField.text.length == 23 && range.length == 0){
return NO; // return NO to not change text
}
if (![originalString isEqualToString:#""] && ![string isEqualToString:#""]) {
NSString *lastChar = [regTextField.text substringFromIndex:[regTextField.text length] - 1];
int modulus = [originalString length] % seperatorInterval;
if (![lastChar isEqualToString:separator] && modulus == 0) {
regTextField.text = [regTextField.text stringByAppendingString:separator];
}
}
[self validateTextFields];
return YES; //Keep accepting input from the user
}
//Validating text field to see if Submit button can be pressed or not
-(IBAction) validateTextFields {
NSString *intString = [NSString stringWithFormat:#"%d", regTextField.text.length];
NSLog(#"Starting %#", intString);
if (regTextField.text.length < 22){
[submitButton setEnabled:NO]; //enables submitButton
}
else {
regTextField.text = [regTextField.text substringToIndex:22];
[submitButton setEnabled:YES]; //disables submitButton
}
intString = [NSString stringWithFormat:#"%d", regTextField.text.length];
NSLog(#"Done %#", intString);
}
You need to add = sign in this if statement
if (regTextField.text.length <= 22){
or just change the number to 23 either way it should work
if (regTextField.text.length < 23){