将电话号码存储为字符串时,如何防止输入错误? [英] How can I prevent bad inputs when storing phone numbers as strings?

查看:157
本文介绍了将电话号码存储为字符串时,如何防止输入错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个可以读取VCards的电话簿程序。问题在于电话号码。通常情况下,它们在美国会是这样的:

I am creating a phonebook program that can read VCards. The problem is with phone numbers. Normally, they will be like this in the United States:

0771234560

但如果电话号码来自外国,则看起来像这样。

But if the phone number is from a foreign country, it would look like this.

+94771234560 或者(22)772324000

现在有 + ()要处理的迹象!我目前正在将电话号码(VCards包含它们作为字符串)转换为数字。但是,如果我将允许的电话号码作为字符串,那么用户可以做一些疯狂的事情,比如在联系表格中插入一个姓名作为电话号码。

Now there are + and () signs to deal with! I am currently converting phone numbers (VCards contain them as Strings) to numbers. However, if I take allow phone numbers as strings, then a user could do something crazy, like insert a name as a phone number in the contact form.

我怎么能将电话号码存储为字符串但会阻止有问题的条目?

How can I store phone numbers as strings but prevent problematic entries?

推荐答案

绝对使用字符串,但验证它。仅仅因为它是一个字符串并不意味着您必须接受任何数据。您应该考虑使用正则表达式(或者可能是一系列正则表达式)来验证数据。

Definitely use a string, but validate it. Just because it's a string doesn't mean you have to accept any data. You should consider using a regular expression (or perhaps a series of regular expressions) to validate the data.

不要只限于特定字符 - 例如,你不想接受)0(作为电话号码 - 使用合理的模式。本地维基百科页面电话号码约定在这方面可能会有所帮助 - 或者您可以寻找其他来源。您可能还希望认为有点宽容,因为不是每个人都会遵循确切的模式。虽然要实现微妙的平衡。

Don't just limit it to specific characters - for example, you don't want to accept ")0(" as a phone number - use sensible patterns. The Wikipedia page on local conventions for phone numbers may prove helpful on this front - or you could look for other sources. You may also want to consider being somewhat lenient, as not everyone will follow exact patterns. There's a delicate balance to be achieved though.

这篇关于将电话号码存储为字符串时,如何防止输入错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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