Having trouble using a regex to validate a phone number. I want to allow only numbers and hyphens, but so far I've been trying to just get numbers working. Unfortunately despite different changes after looking around Google and Stack Overflow, the regex continues to evaluate as false. Ideally, strings such as 8889990000
or 888-999-3333
should both evaluate to true. Any help is appreciated!
Main class code for regex:
boolean correct = PhoneFilter.filterPhone(phone_num);
if (correct == true) {
//create an intent to carry data from main activity to OrderConfirmationActivity
Intent intent = new Intent(MainActivity.this, OrderConfirmationActivity.class);
//pack pizza order data into intent
intent.putExtra("nameSelected", nameEditText.getText().toString());
intent.putExtra("aVariable", type);
intent.putExtra("mtSelected", mt);
intent.putExtra("otSelected", ot);
intent.putExtra("ptSelected", pt);
intent.putExtra("dateSelected", Date);
//start the OrderConfirmationActivity
startActivity(intent);
}
//alert user if phone number entered incorrectly
else if (correct == false) {
AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
alertDialog.setTitle("Alert");
alertDialog.setMessage("Please enter a phone number in either 000-0000-000 format or 0000000000 format");
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}
The code for filterPhone
is:
public class PhoneFilter {
public static boolean filterPhone(String phone_text) {
boolean correct;
if ((phone_text.length() <= 12) && (phone_text.matches("[0-9]+")))
correct = true;
else
correct = false;
System.out.println("correct =" + correct);
return correct;
//InputFilter lengthFilter = new InputFilter.LengthFilter(12);
}
}