I'm new to iOS development. I want to know about how we can validate text field if it contains number with some specific range, say 10 for contact number ? Is there any predefined function available ?
Thank you.
+ (BOOL) validatePassword:(NSString *)passWord
{
NSString *passWordRegex = #"^[a-zA-Z0-9]{6,20}+$";
NSPredicate *passWordPredicate = [NSPredicate predicateWithFormat:#"SELF MATCHES %#",passWordRegex];
return [passWordPredicate evaluateWithObject:passWord];
}
To have textfield to accept only numbers and only till 10 digit length you can use this function.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSString *acceptedCharsters = #"0123456789";
NSUInteger newLength = [textField.text length] + [string length] - range.length;
return (newLength > 10) ? NO : YES;
NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:acceptedCharsters] invertedSet];
NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:#""];
return [string isEqualToString:filtered];
return YES;
}
Related
I am working on a login and resister view controller. I am limiting usernames to 12 characters and passwords to 16 using :
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if(textField==self.userField){
NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
return !([newString length] > 12);
}
else if(textField==self.passwordField){
NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
return !([newString length] > 16);
}
return YES;
}
this works well but I also want to limit it to a set of characters to stop unwanted symbols and also Chinese characters. I want to define this set:
#define ACCEPTABLE_CHARACTERS #"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
Not sure how to add it to the method above though and get both working. If I was to check for the character set only and not length the code would be:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:ACCEPTABLE_CHARACTERS] invertedSet];
NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:#""];
return [string isEqualToString:filtered];
}
Not sure how to combine them though. Can someone help me please? Thanks!
You can do it like (I divided it to function for more readability and easy to scale the conditions)
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
return ([self checkLengthOfString:newString inField:textField] && [self checkCharacter:newString]);
}
// Check Length
- (BOOL)checkLengthOfString:(NSString *)text inField:(UITextField *)textField
{
if(textField == self.userField)
{
return !([text length] > 12);
}
else if(textField == self.passwordField)
{
return !([text length] > 16);
}
}
// Check character
- (BOOL)checkCharacter:(NSString *)text
{
BOOL status = YES;
NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:ACCEPTABLE_CHARACTERS] invertedSet];
NSRange r = [text rangeOfCharacterFromSet:s];
if (r.location != NSNotFound)
{
status = NO;
}
return status;
}
Why don't you just use a regEx to match that chars?
I know this has already been answered, but I had a similar scenario and I found none of the answers on StackOverflow handled the Backspace character.
I needed to limit input into a UITextField to a specific number of AlphaNumeric characters, but be able to enter spaces.
Also, using [textField length] > kMAXNUMCHARS caused a problem: you couldn't backspace once you hit the max number of chars.
So here's my complete solution. It also disallows leading spaces. Trailing spaces are trimmed elsewhere when the value is saved (in my case to a PLIST file)
In my Constants.h file I defined:
#define ALLOWED_CHARECTERS #" ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
extern const int kMAXUSERNAMELENGTH;
then in Constants.m:
const int kMAXUSERNAMELENGTH = 9;
I define my class as UITextFieldDelegate with the line
[self._txtUsername.textField setDelegate:self];
Don't forget to declare the UITextFieldDelegate protocol in your class definiion
#interface MyClass : CCNode <UITextFieldDelegate>
And finally,
//UITextFiledDelegate Protocol method
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
//disallow leading spaces. must allow trailing spaces- never know if we'll add another char
//we trim trailing spaces when we save the TextField value, in our case to Plist file
if (range.location == 0 && [string isEqualToString:#" "])
return NO;
//we use defined ALLOWED_CHARECTERS so we can add chars later, easily.
//we could use [NSCharacterSet alphanumericCharacterSet] if we don't need to allow spaces
NSCharacterSet *allowedInput = [NSCharacterSet characterSetWithCharactersInString:ALLOWED_CHARECTERS];
NSArray* arChar = [string componentsSeparatedByCharactersInSet:allowedInput]; //arChar.count = 1 if 'allowedInput' not in 'string'
//disallow input if its not a backspace (replacementString paramater string equal #"" if a backspace) AND
//(disallow input >= kMAXUSERNAMELENGTH chars, OR disallow if not in allowed allowedChar set
if ( ![string isEqual:#""] && ( [textField.text length] >= kMAXUSERNAMELENGTH || !([arChar count] > 1)) )
return NO;
return YES;
}
I hope this helps someone.
I want the textfield to allow the user to paste only numbers from the alphanumeric text and the same should be displayed.I have already dealt with the keypad part.I have tried the delegate method but it restricts the text altogether ,if it contains any alphabet ,which is not my requirement.
I have gone through the discussions but couldn't find what i was looking for.Suggestions please!!
Try this
Make a macro
#define ACCEPTABLE_CHARECTERS #"0123456789."
And use it
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if (textField==textFieldAmount)
{
NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:ACCEPTABLE_CHARECTERS] invertedSet];
NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:#""];
return [string isEqualToString:filtered];
}
return YES;
}
Check Your textfield containing only numbers or not by using below code :
BOOL valid;
NSCharacterSet *alphaNums = [NSCharacterSet decimalDigitCharacterSet];
NSCharacterSet *inStringSet = [NSCharacterSet characterSetWithCharactersInString:myInputField.text];
valid = [yourTextFieldText isSupersetOfSet:inStringSet];
if (!valid)
{
// Not numeric
}
else
{
//valid number
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSCharacterSet *characterSet = [[NSCharacterSet characterSetWithCharactersInString:#"0123456789"] invertedSet];
NSString *filtered = [[string componentsSeparatedByCharactersInSet:characterSet] componentsJoinedByString:#""];
textField.text = filtered;
return NO;
}
I have to format input string as phone number.For i am using
(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSUInteger newLength = [textField.text length] + [string length] - range.length;
NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:NUMBERS_ONLY] invertedSet];
NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:#""];
if (string.length==3||string.length==7) {
filtered =[filtered stringByAppendingString:#"-"];
}
return (([string isEqualToString:filtered])&&(newLength <= CHARACTER_LIMIT));
}
here
#define NUMBERS_ONLY #"1234567890-"
#define CHARACTER_LIMIT 12
but its not editing back.
Please give some ideas
The method you're using is a UITextFieldDelegate method that determines whether or not to allow a change to the text field - given the range and replacement text, should the change be made (YES or NO).
You're trying to format a string while it is being typed - for this you'll also need to update the value of the textField.text property. This could be done in the same method while returning a "NO" afterwards.
For validation,
- (BOOL) isValidPhoneNumber
{
NSString *numberRegex = #"(([+]{1}|[0]{2}){0,1}+[0]{1}){0,1}+[ ]{0,1}+(?:[-( ]{0,1}[0-9]{3}[-) ]{0,1}){0,1}+[ ]{0,1}+[0-9]{2,3}+[0-9- ]{4,8}";
NSPredicate *numberTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#",numberRegex];
return [numberTest evaluateWithObject:self.inputString];
}
You can use this for formatting the string,
self.inputString = #"1234567890"
NSArray *stringComponents = [NSArray arrayWithObjects:[self.inputString substringWithRange:NSMakeRange(0, 3)],
[self.inputString substringWithRange:NSMakeRange(3, 3)],
[self.inputString substringWithRange:NSMakeRange(6, [self.inputString length]-6)], nil];
NSString *formattedString = [NSString stringWithFormat:#"%#-%#-%#", [stringComponents objectAtIndex:0], [stringComponents objectAtIndex:1], [stringComponents objectAtIndex:2]];
I am having a UITextField in which I had limited the number of characters to 4 before decimal and 3 to after decimal. I have done this through
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range
replacementString:(NSString *)string{
if (textField == txt_weightKg)
{
NSString *newString = [textField.text stringByReplacingCharactersInRange:range
withString:string];
NSString *expression = #"^([0-9]{1,4}+)?(\\.([0-9]{1,3})?)?$";
NSRegularExpression *regex = [NSRegularExpression
regularExpressionWithPattern:expression
options:NSRegularExpressionCaseInsensitive
error:nil];
NSUInteger numberOfMatches = [regex numberOfMatchesInString:newString
options:0
range:NSMakeRange(0,
[newString length])];
if (numberOfMatches == 0)
return NO;
}
return YES;
}
This is only for keeping the validation but now I want i actually want is that As soon as I start typing in the UITextfield a decimal is automatically appended with the number. The second condition is that as I reaches the 4 digits the next digit should be after the decimal. For example:-
if I entered 1 it should look like 1. , for 2 digits 11. this has to continue up to 4 digits and then as soon as I eneter the fifth digit it should place that 5th digit after the decimal as 1111.1 which will continue to 3 places after decimal.
If somebody can help me then It will be greatly appreciated! feel free to ask in case of confusion.
I think i achieved what you required by following code:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
//create character set containing numbers only
NSCharacterSet * set = [[NSCharacterSet characterSetWithCharactersInString:#"0123456789"] invertedSet];
if (textField.text.length >= 8 && range.length == 0)
{
return NO;
}
else
{
if ([string rangeOfCharacterFromSet:set].location != NSNotFound) {
return NO;
}
else
{
int length = [textField.text length];
//append a decimal after 4 digits
if([textField.text length] ==4 && string.length != 0)
{
textField.text = [NSString stringWithFormat:#"%#.",textField.text];
}
return YES;
}
}
}
Please confirm your response to this.
I want to validate length and restrict Numeric, alphanumeric, and alpha characters only in iOS, can anyone help me out to achieve this.
You can form regular expression strings and use it. Please find a sample a code below for allowing only alphabets and space.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSString *stringPlace = #"[a-z A-Z]*";
NSPredicate *testPlace = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", stringPlace];
BOOL matches = [testPlace evaluateWithObject:string];
// if it does not match the regular expression and more than 5 characters
if (!matches && string.length > 5)
{
return NO;
}
return YES;
}
Found best Way to tackle this thing. Works like a champ :)
inside .m file
//#define CHARACTERS #" ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
//#define CHARACTERS_NUMBERS [CHARACTERS stringByAppendingString:#"1234567890"]
///// Inside shouldChangeCharactersInRange
///////////>>>>>>>>>>>>>>>>>>
if(textField== txtFldAlpha)
{
//Alpha only
NSUInteger newLength = [textField.text length] + [string length] - range.length;
NSCharacterSet *unacceptedInput =
[[NSCharacterSet characterSetWithCharactersInString:CHARACTERS] invertedSet];
// Create array of strings from incoming string using the unacceptable
// characters as the trigger of where to split the string.
// If array has more than one entry, there was at least one unacceptable character
if ([[string componentsSeparatedByCharactersInSet:unacceptedInput] count] > 1)
return NO;
else
return YES&&(newLength < 26);
return YES;
}
///////////<<<<<<<<<<<<<<<<<<
///////////>>>>>>>>>>>>>>>>>>
if(textField==txtFldNumeric)
{
//Num only
NSUInteger newLength = [textField.text length] + [string length] - range.length;
NSCharacterSet *nonNumberSet = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
if ([[string componentsSeparatedByCharactersInSet:nonNumberSet] count] > 1)
return NO;
else
return YES&&(newLength < 6);
return YES;
}
///////////<<<<<<<<<<<<<<<<<<
///////////>>>>>>>>>>>>>>>>>>
if(textField==txtFieldNumAlphaSpecial)
{
//Num,Alpha,Special field
NSUInteger newLength = [textField.text length] + [string length] - range.length;
return (newLength > 50) ? NO : YES;
}
///////////<<<<<<<<<<<<<<<<<<