how to validate Zipcode for US or Canada in iOS? - objective-c

I want to know that is there any way to validate the the zipcode of US or Zipcode of Canada?I have tried to use regex.
Like for US
- (BOOL)validateZip:(NSString *)candidate {
NSString *emailRegex = #"(^{5}(-{4})?$)|(^[ABCEGHJKLMNPRSTVXY][A-Z][- ]*[A-Z]$)";
NSPredicate *emailTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", emailRegex];
return [emailTest evaluateWithObject:candidate];
}
but it's not working.Please any body have any idea regarding this validation.if any rest api is there for the validation?Please guide me if possible?

For the US, you have the quantifiers ({5}, {4}, ?) correct but forgot to specify exactly what you're quantifying. You want:
(^[0-9]{5}(-[0-9]{4})?$)
For Canada, according to Wikipedia, the format is A0A 0A0, so I would do:
(^[a-zA-Z][0-9][a-zA-Z][- ]*[0-9][a-zA-Z][0-9]$)
Now, I'd write the complete expression like this, with case insensitivity enabled:
#"^(\\d{5}(-\\d{4})?|[a-z]\\d[a-z][- ]*\\d[a-z]\\d)$"
Frankly, I'm not actually familiar with Objective C or iOS, and sadly I haven't tested the above. However, previously I've seen such posts mention NSRegularExpression, which is missing in your code, but perhaps isn't necessary. Take a look at others' examples to see what other simple errors you might be making. Good luck.

We used this but its only for UK Postcodes. See #acheong87 answer to alter the regex to fit your criteria and other good answers.
NSString *postcodeRegex = #"[A-Z]{1,2}[0-9R][0-9A-Z]?([0-9][ABD-HJLNP-UW-Z]{2}";//WITH SPACES
NSPredict *postcodeValidate = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", postcodeRegex];
if ([postcodeValidate evaluateWithObject:postcodeField.text] == YES) {
NSLog (#"Postcode is Valid");
} else {
NSLog (#"Postcode is Invalid");
}
I advise you test the regex first using this great tool http://www.regexr.com
EDIT
Current regex does not support spaces in postcode after further testing. This will fix that issue.
NSString *postcodeRegex = #"[A-Z]{1,2}[0-9R][0-9A-Z]?(\s|)([0-9][ABD-HJLNP-UW-Z]{2}";//WITH SPACES

Related

stringByAddingPercentEscapesUsingEncoding was deprecated in 9.0 .How to do this?

I'm a junior developer, and I got a code for this:
(NSString *)encodedStringFromObject:(id)object {
return [[object description] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
}
But in 9.0 have to use stringByAddingPercentEncodingWithAllowedCharacters.
How Could I transfer this code ?
I need help, Thanks!
If you want just fast example look at this code:
NSString * encodedString = [#"string to encode" stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];
Also check List of predefined characters sets
If you want explanation read the documents or at least this topic: How to encode a URL in Swift
URL = [[NSString stringWithFormat:#"%#XYZ",API_PATH]stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
You'd read the spec for both functions. Then you would find out for what purpose characters are replaced with escape sequences. From there you would find out the set of allowed characters, which must be documented somewhere.
That's an essential part of changing from junior to normal to senior developer: Find out exactly what your code is supposed to do, which should be defined somewhere, and then make it do what it should do.
stringByAddingPercentEscapesUsingEncoding is probably deprecated because it doesn't know which characters are allowed and sometimes gives the wrong results.
You can use stringByRemovingPercentEncoding instead of stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding
[#"string" stringByRemovingPercentEncoding];
Here is solution to do in Swift
var encodedString = "Hello, playground".addingPercentEncoding(withAllowedCharacters: .urlFragmentAllowed)

Objective C - NSRange and rangeOfString

I have a little problem with NSRange and rangeOfString. I want to search a substring in a given string which is working fine, but only to find a exact string and theres the problem i need to find a substring which begins always the same and ends always the same. I tried it already with something like that:
match = [strIn rangeOfString: #"truni/begin/*/end"];
But thats not working. So i need a way to to do this. Here is the specific part of the Code in full:
NSRange match;
match = [strIn rangeOfString: #"turni/begin/sHjeUUej/end"];
NSRange range = NSMakeRange(match.location, match.length);
NSString *strOut = [strIN substringWithRange:range];
You see the string "turni/begin/sHjeUUej/end" will always be the same except for the part "sHjeUUej". Hope someone can help me.
Thanks in advance.
Use a regular expression with:
- (NSRange)rangeOfString:(NSString *)aString options:(NSStringCompareOptions)mask
with an option of RegularExpressionSearch.
See ICU User Guide Regular Expressions for information on creating regular expressions.
you can use prefix/suffix
if ([strIn hasPrefix:#"truni/begin/"] && [strIn hasSuffix:#"end"]) {
//match
You can use a simpler solution if you make sure that your string always starts with turni/begin/ and ends with /end.
You can use:
NSString *strOut = [[strIn stringByReplacingOccurrencesOfString:#"turni/begin/" withString:#""] stringByReplacingOccurrencesOfString:#"/end" withString:#""];
With that, you can retrieve the string between the two others with only one line of code and less comparations.

need help on a simple predicate to match any word in a string to a property

Let's say i want to let user search for my objects using a name property of the objects.
I have no problem if the user only enters one word:
e.g: facial
My predicate will be:
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"name CONTAINS[cd] %#", word];
But what if user enter more than one word separated by space?
I want to do sth like:
NSArray *words = [query componentsSeparatedByString:#" "];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"name CONTAINS[cd] ANY %#", words];
But it doesnt work. Any guidance?
Thanks!
Another way of doing this (and I just learnt this myself as a result of your question) is to use subqueries. Check this SO question for more details. You can use subqueries in the following manner –
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"SUBQUERY(%#, $str, SELF CONTAINS[cd] $str).#count != 0", words];
NSLog(#"%#", [array filteredArrayUsingPredicate:predicate]);
This seems to work as I've tested it myself but this could also be the arcane & obscure way that Dave has mentioned as it finds no mention in the Predicate Programming Guide.
The format for a SUBQUERY can be found here. It's the same link that you will find in the question linked earlier.
As you mentioned (correctly) in the comment, you can do this by building a compound predicate predicate, although you'll want to use orPredicateWithSubpredicates, and not the and variant.
That really is the best way to do this. There are others, but they rely on more arcane and obscure uses of NSPredicate, and I really recommend going with the build-a-compound-predicate route.

Check that an email address is valid on iOS [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Best practices for validating email address in Objective-C on iOS 2.0?
I am developing an iPhone application where I need the user to give his email address at login.
What is the best way to check if an email address is a valid email address?
Good cocoa function:
-(BOOL) NSStringIsValidEmail:(NSString *)checkString
{
BOOL stricterFilter = NO; // Discussion http://blog.logichigh.com/2010/09/02/validating-an-e-mail-address/
NSString *stricterFilterString = #"^[A-Z0-9a-z\\._%+-]+#([A-Za-z0-9-]+\\.)+[A-Za-z]{2,4}$";
NSString *laxString = #"^.+#([A-Za-z0-9-]+\\.)+[A-Za-z]{2}[A-Za-z]*$";
NSString *emailRegex = stricterFilter ? stricterFilterString : laxString;
NSPredicate *emailTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", emailRegex];
return [emailTest evaluateWithObject:checkString];
}
Discussion on Lax vs. Strict - http://blog.logichigh.com/2010/09/02/validating-an-e-mail-address/
And because categories are just better, you could also add an interface:
#interface NSString (emailValidation)
- (BOOL)isValidEmail;
#end
Implement
#implementation NSString (emailValidation)
-(BOOL)isValidEmail
{
BOOL stricterFilter = NO; // Discussion http://blog.logichigh.com/2010/09/02/validating-an-e-mail-address/
NSString *stricterFilterString = #"^[A-Z0-9a-z\\._%+-]+#([A-Za-z0-9-]+\\.)+[A-Za-z]{2,4}$";
NSString *laxString = #"^.+#([A-Za-z0-9-]+\\.)+[A-Za-z]{2}[A-Za-z]*$";
NSString *emailRegex = stricterFilter ? stricterFilterString : laxString;
NSPredicate *emailTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", emailRegex];
return [emailTest evaluateWithObject:self];
}
#end
And then utilize:
if([#"emailString#email.com" isValidEmail]) { /* True */ }
if([#"InvalidEmail#notreallyemailbecausenosuffix" isValidEmail]) { /* False */ }
To check if a string variable contains a valid email address, the easiest way is to test it against a regular expression. There is a good discussion of various regex's and their trade-offs at regular-expressions.info.
Here is a relatively simple one that leans on the side of allowing some invalid addresses through: ^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,6}$
How you can use regular expressions depends on the version of iOS you are using.
iOS 4.x and Later
You can use NSRegularExpression, which allows you to compile and test against a regular expression directly.
iOS 3.x
Does not include the NSRegularExpression class, but does include NSPredicate, which can match against regular expressions.
NSString *emailRegex = ...;
NSPredicate *emailTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", emailRegex];
BOOL isValid = [emailTest evaluateWithObject:checkString];
Read a full article about this approach at cocoawithlove.com.
iOS 2.x
Does not include any regular expression matching in the Cocoa libraries. However, you can easily include RegexKit Lite in your project, which gives you access to the C-level regex APIs included on iOS 2.0.
Heres a good one with NSRegularExpression that's working for me.
[text rangeOfString:#"^.+#.+\\..{2,}$" options:NSRegularExpressionSearch].location != NSNotFound;
You can insert whatever regex you want but I like being able to do it in one line.
to validate the email string you will need to write a regular expression to check it is in the correct form. there are plenty out on the web but be carefull as some can exclude what are actually legal addresses.
essentially it will look something like this
^((?>[a-zA-Z\d!#$%&'*+\-/=?^_`{|}~]+\x20*|"((?=[\x01-\x7f])[^"\\]|\\[\x01-\x7f])*"\x20*)*(?<angle><))?((?!\.)(?>\.?[a-zA-Z\d!#$%&'*+\-/=?^_`{|}~]+)+|"((?=[\x01-\x7f])[^"\\]|\\[\x01-\x7f])*")#(((?!-)[a-zA-Z\d\-]+(?<!-)\.)+[a-zA-Z]{2,}|\[(((?(?<!\[)\.)(25[0-5]|2[0-4]\d|[01]?\d?\d)){4}|[a-zA-Z\d\-]*[a-zA-Z\d]:((?=[\x01-\x7f])[^\\\[\]]|\\[\x01-\x7f])+)\])(?(angle)>)$
Actually checking if the email exists and doesn't bounce would mean sending an email and seeing what the result was. i.e. it bounced or it didn't. However it might not bounce for several hours or not at all and still not be a "real" email address. There are a number of services out there which purport to do this for you and would probably be paid for by you and quite frankly why bother to see if it is real?
It is good to check the user has not misspelt their email else they could enter it incorrectly, not realise it and then get hacked of with you for not replying. However if someone wants to add a bum email address there would be nothing to stop them creating it on hotmail or yahoo (or many other places) to gain the same end.
So do the regular expression and validate the structure but forget about validating against a service.

NSPredicate and Regex

Can someone please help me with using Regex with NSPredicate?
NSString *regex = #"(?:[A-Za-z0-9])";
NSPredicate *pred = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", regex];
if ([pred evaluateWithObject:mystring])
{
//do something
}
testing the above wth mystring - qstring123 doesn't seem to work. I am expecting it to enter the if condition because it supposedly should match the regex.
Besides, I need a regex for alpha numberic allowing commas and spaces.
will this work?
#"(?:[A-Za-z0-9])*(?:,[A-sa-z0-9)*(?:\s[A-sa-s0-9])"
Please help.
From my experimentation, it tries to match the regex against the entire string, and won't match inside a string.
Therefore, the regex [a-zA-Z0-9]+ works, but [a-zA-Z0-9] does not.
With that in mind, you may want to rework your comma-matching predicate, or use a more full-featured regex solution, like the amazingly awesome RegexKit and RegexKitLite.