I am developing an app for iOS 7 in which I want to retrieve user location details.
Now I also want postal code of user. And I want to check on only that page that postal code entered by the user is valid or not.
I want to validate for US and UK.
How to achieve this?
For India, you can use the below method to validate the pincode
-(BOOL)isValidPinCode:(NSString*)pincode {
NSString *pinRegex = #"^[0-9]{6}$";
NSPredicate *pinTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", pinRegex];
BOOL pinValidates = [pinTest evaluateWithObject:pincode];
return pinValidates;
}
For US, you can use
^\d{5}(-\d{4})?$
For UK, use this
^([A-PR-UWYZ]([0-9]{1,2}|([A-HK-Y][0-9]|[A-HK-Y][0-9]([0-9]|[ABEHMNPRV-Y]))|[0-9][A-HJKS-UW])\ [0-9][ABD-HJLNP-UW-Z]{2}|(GIR\ 0AA)|(SAN\ TA1)|(BFPO\ (C\/O\ )?[0-9]{1,4})|((ASCN|BBND|[BFS]IQQ|PCRN|STHL|TDCU|TKCA)\ 1ZZ))$
Swift 3.0
For US, you can use the below method to validate the ZipCode
func validZipCode(postalCode:String)->Bool{
let postalcodeRegex = "^[0-9]{5}(-[0-9]{4})?$"
let pinPredicate = NSPredicate(format: "SELF MATCHES %#", postalcodeRegex)
let bool = pinPredicate.evaluate(with: postalCode) as Bool
return bool
}
You can use this answer to get postal code.
Get the Zip Code of the Current Location - iPhone SDK
As for validation, it will depend on the country the postal code is in, but this may be a good starting point.
how to validate Zipcode for US or Canada in iOS?
Related
Is it possible to spoof network providers just like it is possible to spoof locations in iOS?
I have an app that will get a user's ISO country code using Core Location, however I would like a fallback for when the user doesn't authorize location services for my app.
I have a function that is called in order to set a user's country according to their carrier; see below.
- (void)carrierBasedLocationSet {
if (DefaultCountryCode && ![DefaultCountryCode isEqualToString:#"Default"]) {
////NSLog(#"Skip Carrier Based Location set : DefaultCountryCode is [%#]", DefaultCountryCode);
return;
}
/***********************************
* Set country code based on Carrier
***********************************/
CTTelephonyNetworkInfo *networkInfo = [[CTTelephonyNetworkInfo alloc] init];
Carrier = [networkInfo subscriberCellularProvider];
NSString *isoCountryCode = Carrier.isoCountryCode;
if (isoCountryCode == nil || isoCountryCode.length == 0) {
isoCountryCode = [[NSLocale currentLocale] objectForKey:NSLocaleCountryCode];
}
self.ISO_CountryCode = [isoCountryCode uppercaseString];
self.CarrierBased_ISO_Country = self.ISO_CountryCode;
}
This code works and produces US, which is where I am located. However, I want to test this out for different countries. Simply editing the product scheme to spoof a location in Australia, for example, does not give me back the AU country code and still gives me US.
Does anyone know if what I am trying to do is possible? Getting a user's location is essential to my application and I am unsure of another alternative.
In Contact apps there's group like "iCloud", "yahoo", "gmail". In swift, is it possible to fetch contact from gmail source only?
Tested code. Hope it will solve your problem...
func getAppropriateName(for container: CNContainer?) -> String? {
var name = ""
if (container?.name == "Card") || container?.name == nil {
name = "iCloud"
}
else if (container?.name == "Address Book") {
name = "Google"
}
else if (container?.name == "Contacts") {
name = "Yahoo"
}
else {
name = "Facebook"
}
return name
}
iCloud/yahoo/gmail etc are CNContainer. Gmail/iCloud is of type CNContainerTypeCardDAV. So first you need to fetch all contacts, and then filter the array based on the CNContainerType of that contact. But unfortunately, we cannot identify which CardDav is it, i.e iCloud/Gmail.
Please see more details here: How do we know which CNContainer represents iCloud?
You can achieve this by looking at Contacts framework runtime headers here: https://github.com/JaviSoto/iOS10-Runtime-Headers/tree/master/Frameworks/Contacts.framework
You can call them by performSelector message. It's a bit messy, but works.
Generally what you have to do is following:
CNContactStore* store = [CNContactStore new];
// fetch accounts that sync contacts with your device (array of CNAccount)
// since CNAccount class isn't available by default, we treat it as NSObject for our puproses
NSArray* accounts = [store performSelector:#selector(accountsMatchingPredicate:error:) withObject:nil withObject:nil];
// you can iterate through this array, I just use first one for this example
NSObject* account = [accounts firstObject];
// get identifier of the account for NSPredicate we use next
NSString* accountId = [account performSelector:#selector(identifier)];
// Display name of the account (aka Yahoo, Gmail etc.)
NSString* accountName = [account performSelector:#selector(_cnui_displayName)];
// NSPredicate that help us to get corresponding CNContainer
NSPredicate* containerPredicate = [[CNContainer class] performSelector:#selector(predicateForContainersInAccountWithIdentifier:) withObject:accountId];
// Fetching CNContainer
CNContainer* container = [[store containersMatchingPredicate:containerPredicate error:nil] firstObject];
After that it's all about general usage of CNContainers.
Hope it will help.
PS. It works on iOS 10, for future versions you should check for Contacts.framework runtime changes.
PPS. I didn't check on swift, but should work either.
Sorry for my english.
Good luck :)
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 domain name valid or not?
If it's really important to you then you could attempt to look-up the MX record of the domain specified, via DNS.
See this answer for (Linux) C code to do that.
To check email address :-
NSString *emailRegex = #"[A-Z0-9a-z._%+-]+#[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
NSPredicate *emailTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", emailRegex];
if( [emailTest evaluateWithObject:email]){
//Valid email
}else{
//Wrong Email id
}
We can check domain name but we can't say that this is valid or not because domain name is not fixed
ex:- 1)abc#abc.com
2) abc#gmail.com
3) abc#yahoo.com
4) abc#abc.in
We can check specific domain name as email address contains "gmail.com" or "yahoo.com"
It's not fix because domain name format is not fix.
It might be like :-
1) aaa#aaa-a.com
2) aaa#aaa.co.in
3) aaa#hotmail.com
4) aaa#facebook.com
Below is what I use for email validation.
NSString *emailRegex = #"^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*#[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
NSPredicate *emailTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", emailRegex];
if (![emailTest evaluateWithObject:emailTF.text]) {
// wrong email
} else {
// right email...
}
Edit 1
If you want to check for domain, go with below.
NSPredicate *websitePredicate = [NSPredicate predicateWithFormat:#"SELF MATCHES %#",#"^[A-Za-z0-9]+(.[A-Za-z0-9-:;\?#_]+)+"];
if ([websitePredicate evaluateWithObject:#"google.com"]) {
NSLog(#"valid domain");
} else {
NSLog(#"not valid domain");
}
I hope you are looking for this...
Edit 2
If you are looking for actual validation of domain name (& not format of domain), then you should follow #trojanfoe answer
As #trojanfoe suggested, using MX record lookup you can check whether entered domain is a mail server. Here is an objective c version of MX record lookup, you need to initialize DNSServiceRef with kDNSServiceType_MX service type.
Another, the most reliable option to check whether user provided valid e-mail address or not would be sending e-mail with confirmation code to the entered e-mail address.
Good luck!
In my iOS app I have to convert a phone number (taken in the contacts) and convert it in international format (to send SMS automatically with an extern library). I saw libPhoneNumber but the problem is that we have to enter the country code, and the app have to work in all (almost) countries, so I don't know what is the user's country.
Here is how the library works :
let phoneUtil = NBPhoneNumberUtil()
let phoneNumberConverted = try phoneUtil.parse("0665268242", defaultRegion: "FR") // So I don't know the country of the user here
print(try? phoneUtil.format(phoneNumberConverted, numberFormat: NBEPhoneNumberFormat.INTERNATIONAL))
formattedPhoneNumberSubstring takes a partial phone number string and formats it as the beginning of a properly formatted international number, e.g. "16463" turns to "+1 646-3".
NSString *formattedPhoneNumberSubstring(NSString *phoneNumber) {
NBPhoneNumberUtil *phoneUtil = [NBPhoneNumberUtil sharedInstance];
phoneNumber = [phoneUtil normalizeDigitsOnly:phoneNumber];
NSString *nationalNumber;
NSNumber *countryCode = [phoneUtil extractCountryCode:phoneNumber nationalNumber:&nationalNumber];
if ([countryCode isEqualToNumber:#0])
return phoneNumber;
NSString *regionCode = [[phoneUtil regionCodeFromCountryCode:countryCode] objectAtIndex:0];
NSString *paddedNationalNumber = [nationalNumber stringByPaddingToLength:15 withString:#"0" startingAtIndex:0];
NSString *formatted;
NSString *formattedSubstr;
for (int i=0; i < paddedNationalNumber.length; i++) {
NSError *error = nil;
formattedSubstr = [phoneUtil format:[phoneUtil parse:[paddedNationalNumber substringToIndex:i] defaultRegion:regionCode error:&error]
numberFormat:NBEPhoneNumberFormatINTERNATIONAL error:&error];
if (getExtraCharacters(formattedSubstr) > getExtraCharacters(formatted)) // extra characters means more formatted
formatted = formattedSubstr;
}
// Preparing the buffer for phoneNumber
unichar phoneNumberBuffer[phoneNumber.length+1];
[phoneNumber getCharacters:phoneNumberBuffer range:NSMakeRange(0, phoneNumber.length)];
// Preparing the buffer for formatted
unichar formattedBuffer[formatted.length+1];
[formatted getCharacters:formattedBuffer range:NSMakeRange(0, formatted.length)];
int j=0;
for(int i = 0; i < phoneNumber.length && j < formatted.length; i++) {
while(formattedBuffer[j] != phoneNumberBuffer[i]) j++;
j++;
}
return [formatted substringToIndex:j];
}
You can get the region using either the users locale or the users geo position.
See stackoverflow question get device location country code for more details.
If you don’t know the country code of a phone number, you can’t generate the international format of it.
You could try using the location of the phone or its region settings to guess the country code, but it won’t be reliable. For example, my phone number is Spanish, I’m currently in Italy and my region is set to New Zealand. My contact list contains numbers from all over the world, and if they weren’t entered in international format there would be no way to guess what country code to use for each number.
If you absolutely have to guess, the best approach might be to think about how the phone would interpret the numbers in the contact list itself. This would require you to determine the country code of the phone’s SIM card. See this answer to a related question for a way of doing that, or here’s some Swift code I’ve used:
let networkInfo = CTTelephonyNetworkInfo()
if let carrier = networkInfo.subscriberCellularProvider {
NSLog("Carrier: \(carrier.carrierName)")
NSLog("ISO: \(carrier.isoCountryCode)")
NSLog("MCC: \(carrier.mobileCountryCode)")
NSLog("MNC: \(carrier.mobileNetworkCode)")
}
The ISO country code can be used to look up a country code for dialling; an example table is in the answer linked above.
I've been facing some issue with to valid string with following condition. The respective conditions are as follows:
String should contain MAX length(which is 7) and should not less Than 6
First character must be from A-Z (should consider aUppercase only)
remaining character must contain only digit (0 to 9).
Here is an example of String I want to valid A12342 (desire output with validation)
Thanks in advance ,Any help will be appreciated.If any one need more information about my query please let me know .
-(BOOL)CheckConditionForValidation
{ if([textfield.text isequalToString:#""]){
return FALSE
}
//else if (//validation for my specific number)
//{
//want to implement logic here
//}
}
Try this rejex pattern [A-Z][0-9]{5,6}
check it online with the link Online rejex check
and if it work than use like this
- (BOOL)checkValidation:(UITextField *)textField
{
NSString *rejex = #"<your pattern>";
NSPredicate *emailTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", rejex];
//if rejex fullfil than it will return true else false.
return [emailTest evaluateWithObject:textField.text];
}