简体   繁体   中英

Postal Code Validation in iOS

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM