我们怎样才能Email Validation在edittextin上表演android?我已经通过 google & SO 但我没有找到一种简单的方法来验证它。
Email Validation
edittext
android
要执行电子邮件验证,我们有很多方法,但简单和最简单的方法是 两种方法 。
1- 使用EditText(....).addTextChangedListenerwhich 不断触发EditText boxie email_id 中的每个输入无效或有效
EditText(....).addTextChangedListener
EditText box
/** * Email Validation ex:- tech@end.com */ final EditText emailValidate = (EditText)findViewById(R.id.textMessage); final TextView textView = (TextView)findViewById(R.id.text); String email = emailValidate.getText().toString().trim(); String emailPattern = "[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+"; emailValidate .addTextChangedListener(new TextWatcher() { public void afterTextChanged(Editable s) { if (email.matches(emailPattern) && s.length() > 0) { Toast.makeText(getApplicationContext(),"valid email address",Toast.LENGTH_SHORT).show(); // or textView.setText("valid email"); } else { Toast.makeText(getApplicationContext(),"Invalid email address",Toast.LENGTH_SHORT).show(); //or textView.setText("invalid email"); } } public void beforeTextChanged(CharSequence s, int start, int count, int after) { // other stuffs } public void onTextChanged(CharSequence s, int start, int before, int count) { // other stuffs } });
2-if-else使用条件的 最简单方法。使用 getText() 获取 EditText 框字符串并与为电子邮件提供的模式进行比较。如果模式不匹配或不匹配,按钮的 onClick 会显示一条消息。它不会在 EditText 框中的每个字符输入时触发。如下所示的简单示例。
if-else
final EditText emailValidate = (EditText)findViewById(R.id.textMessage); final TextView textView = (TextView)findViewById(R.id.text); String email = emailValidate.getText().toString().trim(); String emailPattern = "[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+"; // onClick of button perform this simplest code. if (email.matches(emailPattern)) { Toast.makeText(getApplicationContext(),"valid email address",Toast.LENGTH_SHORT).show(); } else { Toast.makeText(getApplicationContext(),"Invalid email address", Toast.LENGTH_SHORT).show(); }