android中的电子邮件和电话号码验证

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22505336/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 06:05:44  来源:igfitidea点击:

Email and phone Number Validation in android

android

提问by user3437313

I have a registration form in my application which I am trying to validate. I'm facing some problems with my validation while validating the phone number and email fields.

我的应用程序中有一个注册表单,我正在尝试验证它。我在验证电话号码和电子邮件字段时遇到了一些验证问题。

Here is my code:

这是我的代码:

private boolean validate() {

    String MobilePattern = "[0-9]{10}";
    //String email1 = email.getText().toString().trim();
    String emailPattern = "[a-zA-Z0-9._-]+@[a-z]+\.+[a-z]+";

    if (name.length() > 25) {

        Toast.makeText(getApplicationContext(), "pls enter less the 25 character in user name", Toast.LENGTH_SHORT).show();
        return true;

    } else if (name.length() == 0 || number.length() == 0 || email.length() == 
             0 || subject.length() == 0 || message.length() == 0) {

        Toast.makeText(getApplicationContext(), "pls fill the empty fields", Toast.LENGTH_SHORT).show();
        return false;

    } else if (email.getText().toString().matches(emailPattern)) { 

        //Toast.makeText(getApplicationContext(),"valid email address",Toast.LENGTH_SHORT).show();
        return true;

    } else if(!email.getText().toString().matches(emailPattern)) { 

        Toast.makeText(getApplicationContext(),"Please Enter Valid Email Address",Toast.LENGTH_SHORT).show();
        return false;

    } else if(number.getText().toString().matches(MobilePattern)) {

        Toast.makeText(getApplicationContext(), "phone number is valid", Toast.LENGTH_SHORT).show();
        return true;

    } else if(!number.getText().toString().matches(MobilePattern)) {

        Toast.makeText(getApplicationContext(), "Please enter valid 10 digit phone number", Toast.LENGTH_SHORT).show();
        return false;
    }

    return false;
}

I have used this code above for the validation. The problem I'm facing is in the phone number and email validation, only one validation is working. For example, if I comment out the phone number validation, the email validation is working properly. If I comment out the email validation, the phone number validation is working. If use both validations, it's not working.

我已经使用上面的代码进行验证。我面临的问题是电话号码和电子邮件验证,只有一个验证有效。例如,如果我注释掉电话号码验证,则电子邮件验证工作正常。如果我注释掉电子邮件验证,则电话号码验证有效。如果同时使用这两个验证,则它不起作用。

回答by Shabbir Dhangot

For Email Address Validation

用于电子邮件地址验证

private boolean isValidMail(String email) {

    String EMAIL_STRING = "^[_A-Za-z0-9-\+]+(\.[_A-Za-z0-9-]+)*@"
            + "[A-Za-z0-9-]+(\.[A-Za-z0-9]+)*(\.[A-Za-z]{2,})$";

    return Pattern.compile(EMAIL_STRING).matcher(email).matches();

}

OR

或者

private boolean isValidMail(String email) {
   return android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
}

For Mobile Validation

用于移动验证

For Valid Mobile You need to consider 7 digit to 13 digit because some country have 7 digit mobile number. If your main target is your own country then you can match with the length. Assuming India has 10 digit mobile number. Also we can not check like mobile number must starts with 9 or 8 or anything.

对于有效手机,您需要考虑 7 位至 13 位,因为某些国家/地区有 7 位手机号码。如果您的主要目标是您自己的国家,那么您可以匹配长度。假设印度有 10 位手机号码。我们也无法检查手机号码必须以 9 或 8 或任何开头。

For mobile number I used this two Function:

对于手机号码,我使用了这两个功能:

private boolean isValidMobile(String phone) {
    if(!Pattern.matches("[a-zA-Z]+", phone)) {
        return phone.length() > 6 && phone.length() <= 13;
    }
    return false;
}

OR

或者

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

回答by Nambi

Use Patternpackage in Android to match the input validation for email and phone

使用PatternAndroid中的包来匹配电子邮件和电话的输入验证

Do like

喜欢

android.util.Patterns.EMAIL_ADDRESS.matcher(input).matches();
android.util.Patterns.PHONE.matcher(input).matches();

回答by Thomas Bouron

Android has build-in patternsfor email, phone number, etc, that you can use if you are building for Android API level 8 and above.

Android 具有用于电子邮件、电话号码等的内置模式,如果您正在为 Android API 级别 8 及更高级别构建,则可以使用这些模式。

private boolean isValidEmail(CharSequence email) {
    if (!TextUtils.isEmpty(email)) {
        return Patterns.EMAIL_ADDRESS.matcher(email).matches();
    }
    return false;
}

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

回答by Akshay

Try this

尝试这个

public class Validation {

    public final static boolean isValidEmail(CharSequence target) {
        if (target == null) {
        return false;
        } else {
        return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
        }
    } 

    public static final boolean isValidPhoneNumber(CharSequence target) {
        if (target.length()!=10) {
            return false;
        } else {
            return android.util.Patterns.PHONE.matcher(target).matches();
        }
    }

}

回答by Ravinder Payal

He want an elegant and proper solution try this small regex pattern matcher.

他想要一个优雅而适当的解决方案,试试这个小的正则表达式模式匹配器。

This is specifically for India.(First digit can't be zero and and then can be any 9 digits) return mobile.matches("[1-9][0-9]{9}");

这是专门针对印度的。(第一个数字不能是零,然后可以是任何 9 个数字) return mobile.matches("[1-9][0-9]{9}");

Pattern Breakdown:-

模式分解:-

[1-9]matches first digit and checks if number(integer) lies between(inclusive) 1 to 9 [0-9]{9}matches the same thing but {9}tells the pattern that it has to check for upcoming all 9 digits.

[1-9]匹配第一个数字并检查 number(integer) 是否位于(inclusive) 1 到 9 之间 [0-9]{9}匹配相同的东西,但{9}告诉模式它必须检查即将到来的所有 9 位数字。

Now the {9} part may vary for different countries so you may have array which tells the number of digits allowed in phone number. Some countries also have significance for zero ahead of number, so you may have exception for those and design a separate regex patterns for those countries phone numbers.

现在 {9} 部分可能因不同的国家/地区而异,因此您可能有一个数组,它告诉电话号码中允许的位数。某些国家/地区的数字前面的零也很重要,因此您可能有例外,并为这些国家/地区的电话号码设计单独的正则表达式模式。

回答by Ganesh Giri

try this:

尝试这个:

extMobileNo.addTextChangedListener(new MyTextWatcher(extMobileNo));

private boolean validateMobile()    {   

    String mobile =extMobileNo.getText().toString().trim();
    if(mobile.isEmpty()||!isValidMobile(mobile)||extMobileNo.getText().toString().toString().length()<10 || mobile.length()>13 )

    {
            inputLayoutMobile.setError(getString(R.string.err_msg_mobile));
        requestFocus(extMobileNo);
        return false;
    }

    else {
        inputLayoutMobile.setErrorEnabled(false);
    }

    return true;
}

private static boolean isValidMobile(String mobile)
{
    return !TextUtils.isEmpty(mobile)&& Patterns.PHONE.matcher(mobile).matches();
}

回答by Vickie Kangare

public boolean checkForEmail() {
        Context c;
        EditText mEtEmail=(EditText)findViewById(R.id.etEmail);
        String mStrEmail = mEtEmail.getText().toString();
        if (android.util.Patterns.EMAIL_ADDRESS.matcher(mStrEmail).matches()) {
            return true;
        }
        Toast.makeText(this,"Email is not valid", Toast.LENGTH_LONG).show();
        return false;
    }


    public boolean checkForMobile() {
        Context c;
        EditText mEtMobile=(EditText)findViewById(R.id.etMobile);
        String mStrMobile = mEtMobile.getText().toString();
        if (android.util.Patterns.PHONE.matcher(mStrMobile).matches()) {
            return true;
        }
        Toast.makeText(this,"Phone No is not valid", Toast.LENGTH_LONG).show();
        return false;
    }

回答by Uma Shankar

For check email and phone number you need to do that

要查看电子邮件和电话号码,您需要这样做

public static boolean isValidMobile(String phone) {
    boolean check = false;
    if (!Pattern.matches("[a-zA-Z]+", phone)) {
        if (phone.length() < 9 || phone.length() > 13) {
            // if(phone.length() != 10) {
            check = false;
            // txtPhone.setError("Not Valid Number");
        } else {
            check = android.util.Patterns.PHONE.matcher(phone).matches();
        }
    } else {
        check = false;
    }
    return check;
}

public static boolean isEmailValid(String email) {
    boolean check;
    Pattern p;
    Matcher m;

    String EMAIL_STRING = "^[_A-Za-z0-9-\+]+(\.[_A-Za-z0-9-]+)*@"
            + "[A-Za-z0-9-]+(\.[A-Za-z0-9]+)*(\.[A-Za-z]{2,})$";

    p = Pattern.compile(EMAIL_STRING);

    m = p.matcher(email);
    check = m.matches();

    return check;
}



String enter_mob_or_email="";//1234567890 or [email protected]
if (isValidMobile(enter_mob_or_email)) {// Phone number is valid

}else isEmailValid(enter_mob_or_email){//Email is valid

}else isEmailValid(enter_mob_or_email){//Email is valid

}else{// Not valid email or phone number

}

}

回答by Ketan Ramani

XML

XML

<android.support.v7.widget.AppCompatEditText
    android:id="@+id/et_email_contact"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:inputType="text"
    android:maxLines="1"
    android:hint="Enter Email or Phone Number"/>

Java

爪哇

private AppCompatEditText et_email_contact;
private boolean validEmail = false, validPhone = false;     

et_email_contact = findViewById(R.id.et_email_contact);
et_email_contact.addTextChangedListener(new TextWatcher() {
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        String regex = "^[+]?[0-9]{10,13}$";
        String emailContact = s.toString();
        if (TextUtils.isEmpty(emailContact)) {
            Log.e("Validation", "Enter Mobile No or Email");
        } else {
            if (emailContact.matches(regex)) {
                Log.e("Validation", "Valid Mobile No");
                validPhone = true;
                validEmail = false;
            } else if (Patterns.EMAIL_ADDRESS.matcher(emailContact).matches()) {
                Log.e("Validation", "Valid Email Address");
                validPhone = false;
                validEmail = true;
            } else {
                validPhone = false;
                validEmail = false;
                Log.e("Validation", "Invalid Mobile No or Email");
            }
        }
    }
});

if (validPhone || validEmail) {
    Toast.makeText(this, "Valid Email or Phone no", Toast.LENGTH_SHORT).show();
} else {
    Toast.makeText(this, "InValid Email or Phone no", Toast.LENGTH_SHORT).show();
}

回答by Debojyoti Singha

//validation class

//验证类

public class EditTextValidation {

公共类 EditTextValidation {

public static boolean isValidText(CharSequence target) {
    return target != null && target.length() != 0;
}

public static boolean isValidEmail(CharSequence target) {
    if (target == null) {
        return false;
    } else {
        return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
    }
}

public static boolean isValidPhoneNumber(CharSequence target) {
    if (target.length() != 10) {
        return false;
    } else {
        return android.util.Patterns.PHONE.matcher(target).matches();
    }
}

//activity or fragment

//活动或片段

    val userName = registerNameET.text?.trim().toString()
    val mobileNo = registerMobileET.text?.trim().toString()
    val emailID = registerEmailIDET.text?.trim().toString()

    when {
        !EditTextValidation.isValidText(userName) -> registerNameET.error = "Please provide name"
        !EditTextValidation.isValidEmail(emailID) -> registerEmailIDET.error =
            "Please provide email"
        !EditTextValidation.isValidPhoneNumber(mobileNo) -> registerMobileET.error =
            "Please provide mobile number"
        else -> {
            showToast("Hello World")
        }
    }

**Hope it will work for you... It is a working example.

**希望它对你有用......这是一个有效的例子。