代码信号形式验证与电话号码 [英] codeigniter form validation with phone numbers

查看:162
本文介绍了代码信号形式验证与电话号码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么好方法可以验证在codeigniter中输入的电话号码?

What's a good way to validate phone numbers being input in codeigniter?

这是我第一次编写应用程序,我根本不真正理解regex。 ..

It's my first time writing an app, and I don't really understand regex at all...

电话号码有三个输入字段更容易吗?

Is it easier to have three input fields for the phone number?

欢迎提出建议和解释!谢谢!

Recommendations and explanations are welcome! Thanks!

推荐答案

这里是一个很酷的正则表达式,我发现在网络上。它验证几乎任何美国格式的数字,并将其转换为(xxx)xxx-xxxx。我认为这是伟大的,因为那时人们可以输入任何10位数美国电话号码使用任何格式,他们习惯使用,你得到一个正确格式的数字。

Here's a cool regex I found out on the web. It validates a number in almost any US format and converts it to (xxx) xxx-xxxx. I think it's great because then people can enter any 10 digit US phone number using whatever format they are used to using and you get a correctly formatted number out of it.

这是你可以放到MY_form_validation类中的整个函数。我想要我的表单允许空字段,所以如果你想强制一个值,你必须改变它。

Here's the whole function you can drop into your MY_form_validation class. I wanted my form to allow empty fields so you'll have to alter it if you want to force a value.

function valid_phone_number_or_empty($value)
{
    $value = trim($value);
    if ($value == '') {
        return TRUE;
    }
    else
    {
        if (preg_match('/^\(?[0-9]{3}\)?[-. ]?[0-9]{3}[-. ]?[0-9]{4}$/', $value))
        {
            return preg_replace('/^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/', '($1) $2-$3', $value);
        }
        else
        {
            return FALSE;
        }
    }
}

这篇关于代码信号形式验证与电话号码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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