krishnamurthy
krishnamurthy

Reputation: 1604

how to accept email or phone number in the single edit text

I have only one edit text field to accept email or phone number. how to change the input type based on the 1st character ? based on user input i need to perform different operations.. The main thing is i should identify whether that is email or phone number. how to do this?

Upvotes: 1

Views: 1393

Answers (2)

Daksh Agrawal
Daksh Agrawal

Reputation: 923

Novo Lucas's answer is correct.

My Views :

First thing is that you can't know input type using the first letter cause some email addresses begin with numbers.

On button click you can identify type by knowing if the text contains only numbers or alphanumeric characters. For more info about code you can search it on Google. I will try to add code after some time. Good Luck

Upvotes: 0

Kartik Shandilya
Kartik Shandilya

Reputation: 3924

In your, EditText set a TextWatcher which calls a function to check if the text is email or is a phone number.

Get the text from your TextView like :

String text = textView.getText().toString();

Adding the listener to your TextView :

textView.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(....){}

        @Override
        public void beforeTextChanged(...){}

        @Override
        public void afterTextChanged(Editable s) {
            if(isEmail(text)){//do your stuff}
            if(isPhone(text)){//do your stuff}  
        }
}

Your methods would look something like this:

public static boolean isEmail(String text) {
    String expression = "^[\\w\\.-]+@([\\w\\-]+\\.)+[A-Z]{2,4}$";
    Pattern p = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
    Matcher m = p.matcher(text);
    return m.matches();
}

public static boolean isPhone(String text) {
   if(!TextUtils.isEmpty(text)){
       return TextUtils.isDigitsOnly(text);
   } else{
       return false;
   }
}

This might not be possible with just checking the first digit. Though you can put validations inside onTextChanged method.

Upvotes: 3

Related Questions