How can i find NSString having atlease one charater in iPhone app? - iphone

Am working on Message based iPhone app. I have to pass numbers to Webservice if the k like a-z and A-Z i have alert the user to omit the letters from the numbers. How can i find NSString value having a-z and A-Z letters in it? Anyone please help me. Thanks in advance.

That should be it :)
NSCharacterSet *alphaSet = [NSCharacterSet letterCharacterSet];
BOOL valid = [[yourString stringByTrimmingCharactersInSet:alphaSet] isEqualToString:#""];
It removes all the letters from your string, if there is anything left, then valid is NO.
Hope that helps ! :)

Do this:
NSCharacterSet *alphabetSet = [[NSCharacterSet characterSetWithCharactersInString:#"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLKMNOPQRSTUVWXYZ"] invertedSet];
if ([yourString rangeOfCharacterFromSet:alphabetSet].location == NSNotFound) {
if(yourString.length >= 1)
{
// has aleast one character
}
}

If you just want to check if there is ANY character in your string use something like this:
if ([yourString length] > 0) {
// nice feature here is, this will also work when yourString is nil! :D
}
---
If you want to do a more complex check you will have to use Regular Expressions. Use NSRegularExpression class like this:
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"^[A-Za-z]+$" options:0] error:NULL];
NSUInteger numberOfMatches = [regex numberOfMatchesInString:yourString
options:0
range:NSMakeRange(0, [string length])];
if (numberOfMatches > 0) {
// yourString does only consist of multiple letters
}
^[a-zA-Z]+$ matches only strings that consist of one or more letters only (^ and $ mark the begin and end of a string respectively). ^[0-9]+$ matches numbers only.

NSString * regexName = #"[a-zA-Z] * ";
NSString *testString = #"your string";
NSPredicate *predicate;
predicate = [NSPredicate predicateWithFormat:#"SELF MATCHES %#",regexName];
if ([predicate evaluateWithObject:testString]) {
NSLog(#"true");
}
else{NSLog"string contains numbers or special characters" ;}

From What I understand you want phone Numbers to be entered
First of all you can set the keypad as UIKeyboardTypePhonePad or UIKeyboardTypeNumberPad for the UITextView you are adding the numbers to.
OR
Pass the text to this function
-(BOOL) checkForPhoneNumber:(NSString *) string
{
NSPredicate *confidenceTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#",NUMBER_REGEX];
return [confidenceTest evaluateWithObject:string]?YES:NO;
}
where
#define NUMBER_REGEX #"^[0-9]10?$"

Related

How to validate the textfield with 8 to 15 characters and with strong password [duplicate]

This question already has answers here:
Regular Expression for password in iPhone
(2 answers)
Closed 9 years ago.
I Have a text field that I want to enter password in that.I want to enter strong password.That means 8 to 15 characters in that at least one small Letter,one Capital Letter,1 spacial caracter,one number.
Please give the suggestion.
With
password.length
you can ask for the length of a string. Compare that to your desired limits.
With
- (BOOL)string:(NSString *)text matches:(NSString *)pattern
{
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:nil];
NSArray *matches = [regex matchesInString:text options:0 range:NSMakeRange(0, text.length)];
return matches.count > 0;
}
you have a method that provides regex to strings (you can also implement this as a category to NSString).
The first parameter will be your password, the second will be the pattern.
I am not that good with regex, so there might be better solutions but this would be my way
NSString *password = #"iS_bhd97zAA!";
NSString *scPattern = #"[a-z]";
NSString *cPattern = #"[A-Z]";
NSString *sPattern = #"[!%&\._;,]";
NSString *nPattern = #"[0-9]";
if (8 <= password.length && password.length <= 15 &&
[self string:password matches:scPattern] &&
[self string:password matches:cPattern] &&
[self string:password matches:sPattern] &&
[self string:password matches:nPattern])
{
NSLog(#"PW is valid");
}
Hint
The regex for special characters is tricky because you need to escape some of the chars. Mine might be correct, but I am not absolutely sure.
There is also a possiblility to do this in only one regex, but this looks scary imo
This one
(?=^.{8,}$)((?=.*\d)|(?=.*\W+))(?![.\n])(?=.*[A-Z])(?=.*[a-z]).*$
has everything except the special chars, maybe you want to add that yourself :D
This can be easily done using Regular Expressions. I'm not familiar with Regular Expressions, so I'm suggesting this hard way.
You can use this function for checking this:
- (BOOL)strongPassword:(NSString *)yourText
{
BOOL strongPwd = YES;
//Checking length
if([yourText length] < 8)
strongPwd = NO;
//Checking uppercase characters
NSCharacterSet *charSet = [NSCharacterSet uppercaseLetterCharacterSet];
NSRange range = [yourText rangeOfCharacterFromSet:charSet];
if(range.location == NSNotFound)
strongPwd = NO;
//Checking lowercase characters
charSet = [NSCharacterSet lowercaseLetterCharacterSet];
range = [yourText rangeOfCharacterFromSet:charSet];
if(range.location == NSNotFound)
strongPwd = NO;
//Checking special characters
charSet = [[NSCharacterSet alphanumericCharacterSet] invertedSet];
range = [yourText rangeOfCharacterFromSet:charSet];
if(range.location == NSNotFound)
strongPwd = NO;
return strongPwd;
}
In the delegate method textField:shouldChangeCharactersInRange:replacementString: for the UITextField you need to do the following:
Get text with the property myTextField.text
Check for uppercase and lower case character counts
Similarly check for the special character and the number counts
If all conditions are satisfied process the field else display error.
I would have written down the code for you but its against the SO policies. You attempt writing this code and if you are stuck you can always post another question.

NSString value validation in iOS

This simple validation method for NSString makes trouble.
I have an NSString value and I want to validate the string, i.e, if the string contains only 'a to z' (or) 'A to Z' (or) '1 to 9' (or) '#,!,&' then the string is valid. If the string contains any other values then this the NSString is invalid, how can i validate this..?
As example:
Valid:
NSString *str="aHrt#2"; // something like this
Invalid:
NSString *str="..gS$"; // Like this
Try using character sets:
NSMutableCharacterSet *set = [NSMutableCharacterSet characterSetWithCharactersInString:#"#!&"];
[set formUnionWithCharacterSet:[NSCharacterSet alphanumericCharacterSet]];
if ([string rangeOfCharacterFromSet:[set invertedSet]].location == NSNotFound) {
// contains a-z, A-Z, 0-9 and &#! only - valid
} else {
// invalid
}
I would do something using stringByTrimmingCharactersInSet
Create an NSCharacterSet containing all valid characters, then trim those characters from the test string, if the string is now empty it is valid, if there are any characters left over, it is invalid
NSCharacterSet *validCharacters = [NSCharacterSet characterSetWithCharactersInString:#"myvalidchars"];
NSString *trimmedString = [testString stringByTrimmingCharactersInSet:validCharachters];
BOOL valid = [trimmedString length] == 0;
Edit:
If you want to control the characters that can be entered into a text field, use textField:shouldChangeCharactersInRange:replacementString: in UITextFieldDelegate
here the testString variable becomes the proposed string and you return YES if there are no invalid characters
The NSPredicate class is what you want
More info about predicate programming. Basically you want "self matches" (your regular expression). After that you can use the evaluateWithObject: method.
EDIT Easier way: (nevermind, as I am editing it wattson posted what I was going to)
You can use the class NSRegularExpression to do this.
https://developer.apple.com/library/mac/documentation/Foundation/Reference/NSRegularExpression_Class/Reference/Reference.html
You can also use NSRegularExpression to search your NSString, if it contains only the valid characters (or vice versa).
More info:
Search through NSString using Regular Expression
Use regular expression to find/replace substring in NSString
- (BOOL)validation:(NSString *)string
{
NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:#"1234567890abcdefghik"] invertedSet];
NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:#""];
return ([string isEqualToString:filtered]);
}
In your button action:
-(IBAction)ButtonPress{
if ([self validation:activity.text]) {
NSLog(#"Macth here");
}
else {
NSLog(#"Not Match here");
}
}
Replace this "1234567890abcdefghik" with your letters with which you want to match
+(BOOL) validateString: (NSString *) string
{
NSString *regex = #"[A-Z0-9a-z#!&]";
NSPredicate *test = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", emailRegex];
BOOL isValid = [test evaluateWithObject:string];
return isValid;
}
You can simply do it using NSMutableCharacterSet
NSMutableCharacterSet *charactersToKeep = [NSMutableCharacterSet alphanumericCharacterSet];
[charactersToKeep addCharactersInString:#"#?!"];
NSCharacterSet *charactersToRemove = [charactersToKeep invertedSet]
NSString *trimmed = [ str componentsSeparatedByCharactersInSet:charactersToRemove];
if([trimmed length] != 0)
{
//invalid string
}
Reference NSCharacterSet
You can use regex. If every thing fails use brute force like
unichar c[yourString.length];
NSRange raneg={0,2};
[yourString getCharacters:c range:raneg];
// now in for loop
for(int i=0;i<yourString.length;i++)
{
if((c[i]>='A'&&c[i]<='Z')&&(c[i]=='#'||c[i]=='!'||c[i]=='&'))
{
//not the best or most efficient way but will work till you write your regex:P
}
}

NSString search whole text for another string

I would like to search for an NSString in another NSString, such that the result is found even if the second one does not start with the first one, for example:
eg: I have a search string "st". I look in the following records to see if any of the below contains this search string, all of them should return a good result, because all of them have "st".
Restaurant
stable
Kirsten
At the moment I am doing the following:
NSComparisonResult result = [selectedString compare:searchText options:(NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch) range:NSMakeRange(0, [searchText length])];
This works only for "stable" in the above example, because it starts with "st" and fails for the other 2. How can I modify this search so that it returns ok for all the 3?
Thanks!!!
Why not google first?
String contains string in objective-c
NSString *string = #"hello bla bla";
if ([string rangeOfString:#"bla"].location == NSNotFound) {
NSLog(#"string does not contain bla");
} else {
NSLog(#"string contains bla!");
}
Compare is used for testing less than/equal/greater than. You should instead use -rangeOfString: or one of its sibling methods like -rangeOfString:options:range:locale:.
I know this is an old thread thought it might help someone.
The - rangeOfString:options:range: method will allow for case insensitive searches on a string and replace letters like ‘ö’ to ‘o’ in your search.
NSString *string = #"Hello Bla Bla";
NSString *searchText = #"bla";
NSUInteger searchOptions = NSCaseInsensitiveSearch | NSDiacriticInsensitiveSearch;
NSRange searchRange = NSMakeRange(0, string.length);
NSRange foundRange = [string rangeOfString:searchText options:searchOptions range:searchRange];
if (foundRange.length > 0) {
NSLog(#"Text Found.");
}
For more comparison options NSString Class Reference
Documentation on the method - rangeOfString:options:range: can be found on the NSString Class Reference

Detect Phone number in a NSString

I want to extract the phone number from a NSString.
For ex: In the string Call John # 994-456-9966, i want to extract 994-456-9966.
I have tried code like,
NSString *nameRegex =#"(\(\d{3}\)\s?)?\d{3}[-\s\.]\d{4}";
NSPredicate *nameTest = [NSPredicate predicateWithFormat:#"ANY keywords.name CONTAINS[c] %#",nameRegex];
validationResult=[nameTest evaluateWithObject:phoneNo];
but i couldnt get exact result. Can anyone help me? Thanks in advance.
This is what you are looking for, I think:
NSString *myString = #"John # 123-456-7890";
NSString *myRegex = #"\\d{3}-\\d{3}-\\d{4}";
NSRange range = [myString rangeOfString:myRegex options:NSRegularExpressionSearch];
NSString *phoneNumber = nil;
if (range.location != NSNotFound) {
phoneNumber = [myString substringWithRange:range];
NSLog(#"%#", phoneNumber);
} else {
NSLog(#"No phone number found");
}
You can rely on the default Regular Expression search mechanism built into Cocoa. This way you will be able to extract the range corresponding to the phone number, if present.
Remember do alway double-escape backslashes when creating regular expressions.
Adapt your regex accordingly to the part of the phone number you'd like to extract.
Edit
Cocoa provides really simple tools for handling regular expressions. For more complex needs, you should look at the powerful RegexKitLite extension for Cocoa projects.
You can check the official NSDataDetector in iOS 4.0
phoneLinkDetector = [[NSDataDetector alloc] initWithTypes:
(NSTextCheckingTypeLink | NSTextCheckingTypePhoneNumber) error:nil];
NSUInteger numberOfPhoneLink = [[self phoneLinkDetector] numberOfMatchesInString:tweet
options:0 range:NSMakeRange(0, tweet.length)];
NSString * number = #"(555) 555-555 Office";
NSString * strippedNumber = [number stringByReplacingOccurrencesOfString:#"[^0-9]" withString:#"" options:NSRegularExpressionSearch range:NSMakeRange(0, [number length])];
Result: 555555555
if u need just the number u can filter out the special characters and use nsscanner
NSString *numberString = #"Call John # 994-456-9966";
NSString *filteredString=[numberString stringByReplacingOccurrencesOfString:#"-" withString:#""];
NSScanner *aScanner = [NSScanner scannerWithString:filteredString];
[aScanner scanInteger:anInteger];
Assume that you are having "#" symbol in all phone numbers.
NSString *list = #"Call John # 994-456-9966";
NSArray *listItems = [list componentsSeparatedByString:#"#"]
or
You can use the NSScanner to extract the phone number.
EDIT:After seeing the comments.
Assume that you are having only 12 characters in your mobile numbers.
length=get the total length of the string.
index=length-12;
NSString *str=[myString substringFromIndex:index];

How to test a string for text

I would like to test a string to see if anywhere it contains the text "hello". I would like the test to not take into account capitalization. How can I test this string?
Use the below code as reference to find check for a substring into a string.
NSString* string = #"How to test a string for text" ;
NSString* substring = #"string for" ;
NSRange textRange;
textRange =[string rangeOfString:substring options:NSCaseInsensitiveSearch];
if(textRange.location != NSNotFound)
{
//Does contain the substring
}
-[NSString rangeOfString: options:] will do it.
NSRange range = [string rangeOfString:#"hello" options:NSCaseInsensitiveSearch];
BOOL notFound = range.location==NSNotFound;
I am assuming all words are separated by a space, and that there is no punctuation. If there is punctuation.
NSArray *dataArray = [inputString componentsSeparatedByString:#" "];
for(int i=0; i<[dataArray count]){
if([[dataArray objectAtIndex:i] isEqualToString:#"hello"]){
NSLog(#"hello has been found!!!");
}
}
I haven't tested this but it should work in theory.
Check out the docs for ways to remove punctuation and make the string all lower case. This should be pretty straight-forward.
Other solutions here are good but you should really use a regex,
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"^(hello)*$"
options:NSRegularExpressionCaseInsensitive
error:&error];
Docs are here: http://developer.apple.com/library/ios/#documentation/Foundation/Reference/NSRegularExpression_Class/Reference/Reference.html