如何在 iOS 中验证美国或加拿大的邮政编码? [英] how to validate Zipcode for US or Canada in iOS?

查看:72
本文介绍了如何在 iOS 中验证美国或加拿大的邮政编码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道有什么方法可以验证美国的邮政编码或加拿大的邮政编码吗?我试过使用正则表达式.喜欢美国

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];   
}

但它不起作用.请任何机构对此验证有任何想法.是否有其他 api 用于验证?如果可能,请指导我?

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?

推荐答案

对于美国,你有量词 ({5}, {4}, >?) 正确,但忘记具体说明您要量化的内容.你想要:

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})?$)

对于加拿大,根据维基百科,格式是A0A 0A0,所以我会这样做:

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)$"

坦率地说,我实际上并不熟悉 Objective C 或 iOS,遗憾的是我还没有测试上述内容.但是,以前我看到过这样的帖子提到了 NSRegularExpression,它在您的代码中缺失,但可能不是必需的.看看其他人的例子,看看你可能会犯哪些其他简单的错误.祝你好运.

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.

这篇关于如何在 iOS 中验证美国或加拿大的邮政编码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆