使用国家/地区代码验证手机号码 [英] Validate Mobile number with the country code

查看:738
本文介绍了使用国家/地区代码验证手机号码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想验证用户输入的手机号码.我有两个编辑文本,一个用于代码,即+91,0等,另一个用于电话号码.

I want to validate the mobile number user enters. I have two edit texts one for the code i.e. +91,0 etc and another for the phone number.

我有一个问题,如果用户输入的数字超过10个,如何停止在编辑文本中输入数字.另外,还应使用代码和编号对其进行验证.

I have a question that how to stop entering the numbers in edit text if more than 10 numbers being entered by the user. Also it should get validated with code and the number.

我尝试使用此代码进行验证.

I tried the validation with this code.

 private boolean isValidMobile(String phone)
{
    return android.util.Patterns.PHONE.matcher(phone).matches();
}

 else if (!isValidMobile(code.getText().toString()+mobileNo.getText().toString()))
            {
                Toast.makeText(RegisterActivity.this,"Please enter correct Mobile No.",Toast.LENGTH_LONG).show();
            }

但是该数字不能返回true.始终返回false,即请输入正确的数字.

But it dose not return true for the number. Always returns false i.e. please enter the correct number.

编辑数字文本:

            <EditText
                android:layout_width="30dp"
                android:layout_height="match_parent"
                android:ems="10"
                android:id="@+id/editText_code"
                android:layout_marginLeft="20dp"
                android:background="@android:color/transparent"
                android:hint="+91"
                android:textSize="14sp"
                android:phoneNumber="true" />


      <EditText
                android:layout_width="match_parent"
                android:layout_height="40dp"
                android:hint="MOBILE NO"
                android:singleLine="false"
                android:layout_below="@+id/linearLayoutFirstName"
                android:layout_toRightOf="@+id/linearLayoutFirstName"
                android:layout_toEndOf="@+id/linearLayoutFirstName"
                android:background="@android:color/transparent"
                android:layout_gravity="center"
                android:textSize="12sp"
                android:layout_marginLeft="05dp"
                android:id="@+id/mobileNo"
                android:phoneNumber="true" />
        </LinearLayout>

如何执行此操作?谢谢.

How to do this? Thank you.

推荐答案

尝试以下示例...

activity_main.xml

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<EditText
    android:id="@+id/edtCountryCode"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:inputType="phone"
    android:hint="country_code"/>

<EditText
    android:id="@+id/edtPhoneNumber"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@id/edtCountryCode"
    android:inputType="phone"
    android:hint="phone_no"/>

<TextView
    android:id="@+id/tvIsValidPhone"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/edtPhoneNumber"
    android:layout_marginTop="10dp"
    android:layout_marginBottom="10dp"/>

<Button
    android:id="@+id/btnValidate"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/tvIsValidPhone"
    android:text="validate"/>

 </RelativeLayout>

MainActivity.java

MainActivity.java

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Patterns;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.i18n.phonenumbers.NumberParseException;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.i18n.phonenumbers.Phonenumber;

public class MainActivity extends AppCompatActivity {

TextView tvIsValidPhone;
EditText edtPhone;
EditText edtCountryCode;
Button btnValidate;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    tvIsValidPhone = (TextView) findViewById(R.id.tvIsValidPhone);
    edtCountryCode = (EditText) findViewById(R.id.edtCountryCode);
    edtPhone = (EditText) findViewById(R.id.edtPhoneNumber);
    btnValidate = (Button) findViewById(R.id.btnValidate);
    btnValidate.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String countryCode = edtCountryCode.getText().toString().trim();
            String phoneNumber = edtPhone.getText().toString().trim();
            if(countryCode.length() > 0 && phoneNumber.length() > 0){
                if(isValidPhoneNumber(phoneNumber)){
                    boolean status = validateUsing_libphonenumber(countryCode, phoneNumber);
                    if(status){
                        tvIsValidPhone.setText("Valid Phone Number (libphonenumber)");
                    } else {
                        tvIsValidPhone.setText("Invalid Phone Number (libphonenumber)");
                    }
                }
                else {
                    tvIsValidPhone.setText("Invalid Phone Number (isValidPhoneNumber)");
                }
            } else {
                Toast.makeText(getApplicationContext(), "Country Code and Phone Number is required", Toast.LENGTH_SHORT).show();
            }
        }
    });
}

private boolean isValidPhoneNumber(CharSequence phoneNumber) {
    if (!TextUtils.isEmpty(phoneNumber)) {
        return Patterns.PHONE.matcher(phoneNumber).matches();
    }
    return false;
}

private boolean validateUsing_libphonenumber(String countryCode, String phNumber) {
    PhoneNumberUtil phoneNumberUtil = PhoneNumberUtil.getInstance();
    String isoCode = phoneNumberUtil.getRegionCodeForCountryCode(Integer.parseInt(countryCode));
    Phonenumber.PhoneNumber phoneNumber = null;
    try {
        //phoneNumber = phoneNumberUtil.parse(phNumber, "IN");  //if you want to pass region code
        phoneNumber = phoneNumberUtil.parse(phNumber, isoCode);
    } catch (NumberParseException e) {
        System.err.println(e);
    }

    boolean isValid = phoneNumberUtil.isValidNumber(phoneNumber);
    if (isValid) {
        String internationalFormat = phoneNumberUtil.format(phoneNumber, PhoneNumberUtil.PhoneNumberFormat.INTERNATIONAL);
        Toast.makeText(this, "Phone Number is Valid " + internationalFormat, Toast.LENGTH_LONG).show();
        return true;
    } else {
        Toast.makeText(this, "Phone Number is Invalid " + phoneNumber, Toast.LENGTH_LONG).show();
        return false;
    }
}}

下载jar文件,然后从下面的链接添加到libs文件夹. http://www.java2s.com/Code/Jar/l/Downloadlibphonenumber41jar. htm

Download jar file and add in libs folder from below link.. http://www.java2s.com/Code/Jar/l/Downloadlibphonenumber41jar.htm

这篇关于使用国家/地区代码验证手机号码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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