为什么电子邮件验证总是会在我的应用程

时间:2017-05-07 12:54:03

标签: java android validation android-fragments if-statement

我正在尝试验证电子邮件添加。哪个用户在我的表单中输入但是它总是给出“请输入有效的电子邮件地址”错误,即使我写了真正的电子邮件地址。我应该在电子邮件模式或我的代码中的条件中进行更正?帮助我。

这是我的java文件:

IndividualuserFragment.java:

         public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {

                View rootview = inflater.inflate(R.layout.fragment_individualuser, container, false);
                save = (Button) rootview.findViewById(R.id.save);
                cancel = (Button) rootview.findViewById(R.id.cancel);

                email = (EditText) rootview.findViewById(R.id.editemail);
                password = (EditText) rootview.findViewById(R.id.editpassword);

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

     fm =getFragmentManager();
     cancel.setOnClickListener(new View.OnClickListener(){

                    @Override
                    public void onClick(View v) {
                        fm.beginTransaction().replace(R.id.content_frame,new LoginFragment()).commit();
                    }
                });
                save.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                          if(!(email.getText().toString().matches(emailPattern) && email.getText().toString().length() > 0)){
                            email.setError("please valid email address");
                            email.requestFocus();
                        }
    else if(!(password.getText().toString().length()>=6 && password.getText().toString().length()<=10)){
                            password.setError("please enter valid password");
                            password.requestFocus();
                        }else {

        //                AsyncTask obj = new AsyncDemo();
        //                obj.execute();
                            new myasyncDemo().execute();
                        }
                    }
                });


                return rootview;
            }

2 个答案:

答案 0 :(得分:3)

您可以利用现有的电子邮件验证方法。

   private boolean isValidEmail(final String email) {
     return !TextUtils.isEmpty(email) 
                   && Patterns.EMAIL_ADDRESS.matcher(email).matches();
   } 

答案 1 :(得分:1)

尝试替换email.getText().toString().length() > 0并使用TextUtils.isEmpty(email.getText().toString())

您需要首先检查空字符串条件,然后匹配您的电子邮件条件。

所以你的情况如下:

if(TextUtils.isEmpty(email.getText().toString()) || !Patterns.EMAIL_ADDRESS.matcher(email.getText().toString()).matches()
{
  email.setError("please valid email address");
  email.requestFocus();
}