仅当字段为非空时才进行电子邮件验证

时间:2016-07-22 10:04:29

标签: java android string android-edittext email-validation

此代码适用于用户名和移动设备,根据我的选择,但它不适用于电子邮件验证。 注意我想检查电子邮件只是非空。如何检查电子邮件的验证只有这个字段是非空的。**记住我知道逻辑但是如何把逻辑放在这个代码中因为 **我尝试了几种逻辑,但在电子邮件编辑文本中没有任何作用。

public class Login extends BaseActivity {

    JSONObject jsonobject;
    JSONArray jsonarray;

    private ProgressDialog dialog;



    ArrayList<String> arealist;
    //ArrayList<GetterSetter> area;



    public static final String PREFS_NAME = "MyPrefsFile";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        Button login = (Button) findViewById(R.id.button_register);

        login.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v) {

                EditText user = (EditText) findViewById(R.id.editText_enter_name);
                EditText mobile = (EditText) findViewById(R.id.editText_mobNo);
                EditText email = (EditText) findViewById(R.id.editText_email);




                // Check The Validity of empty fields
                boolean Resp = validate(new EditText[]{user,mobile});


                // Check The Validity of emailID
                    boolean e_valid = isEmailValid(email.getText());

                // Check The Validity of Mobile Numbers
                boolean mobile_valid = isMobValid(mobile.getText());

                if (Resp && mobile_valid && e_valid) {

                    PostJson();
                } else {
                Toast.makeText(Login.this, "Field incorrect..!!!",
                            Toast.LENGTH_SHORT).show();
                }

                if (Resp) {
                    String pass = mobile.getText().toString();
                    String e_check = email.getText().toString();
                    if (TextUtils.isEmpty(pass) || pass.length() < 10) {
                        mobile.setError("Mobile number should be of 10 digits");}

                        else if (e_check!=null || e_check.length() >=1) {

                            email.setError("Email Address in invalid format");

                        Toast.makeText(Login.this,
                                "Email Address in invalid format",
                                Toast.LENGTH_SHORT).show();
                            // Chk Validation of mobile number

                            if (mobile_valid) {

                                if (e_valid) {


                                    if (isInternetPresent) {
                                        // setting progress bar to zero
                                        dialog = new ProgressDialog(Login.this);
                                        dialog.setMessage("Please Wait...");
                                        dialog.setIndeterminate(false);
                                        dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
                                        dialog.setProgressNumberFormat(null);
                                        dialog.setProgress(0);
                                        dialog.show();

//                          Toast.makeText(Login.this, "Connecting....", Toast.LENGTH_LONG)
//                                  .show();

                                    } else {

                                        Toast.makeText(Login.this, "Unable to connect the server, please check your data settings", Toast.LENGTH_LONG)
                                                .show();
                                    }
                                }
                            }
                        }

                    }
                }





            // =====To check the validation of Emails and Empty
            // Fields==========//

            public boolean isEmailValid(Editable email) {
                boolean isValid = false;

                String expression = "^(([\\w-]+\\.)+[\\w-]+|([a-zA-Z]{1}|[\\w-]{2,}))@"
                        + "((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?"
                        + "[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\."
                        + "([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?"
                        + "[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|"
                        + "([a-zA-Z]+[\\w-]+\\.)+[a-zA-Z]{2,4})$";
                CharSequence inputStr = email;

                Pattern pattern = Pattern.compile(expression,
                        Pattern.CASE_INSENSITIVE);
                Matcher matcher = pattern.matcher(inputStr);

                if (matcher.matches()) {
                    isValid = true;
                }

                return isValid;
            }

            public boolean isMobValid(Editable mobile) {

                boolean isOk = false;

                String exp = "^[0-9]{10}$";
                CharSequence inputStr = mobile;

                Pattern pattern = Pattern
                        .compile(exp, Pattern.CASE_INSENSITIVE);
                Matcher matcher = pattern.matcher(inputStr);
                if (matcher.matches()) {
                    isOk = true;
                }
                return isOk;
            }

            public boolean validate(EditText[] fields) {
                // TODO Auto-generated method stub
                for (int i = 0; i < fields.length; i++) {
                    EditText currentField = fields[i];
                    if (currentField.getText().toString().length() <= 0) {

                        currentField.setError("This field can't be empty");
//                      Toast.makeText(Login.this, "Enter all the fields..!!!",
//                              Toast.LENGTH_SHORT).show();
                        return false;
                    }
                }
                return true;
            }
        });
    }

    // ==========//




    // =========================== Json Object==================//

    public void PostJson() {


            }



            @Override
            public void onFailure(Throwable e, String response) {


                Log.e("ERROR_LOG", "onFailure request" + e.toString());
                Toast.makeText(Login.this, "Error in Connection.....",
                        Toast.LENGTH_SHORT).show();

            }

            @Override
            public void onFinish() {
                // //////// { onFinish body}///////////////////////////////
                super.onFinish();


                // ////////////////////////////////////////////////////////

            }
        });
    }


}

3 个答案:

答案 0 :(得分:2)

验证电子邮件ID的

使用Android的默认电子邮件数学家。

android.util.Patterns.EMAIL_ADDRESS.matcher(your data).matches();

例如。

if (etMail.getText().toString().trim().equals("")) {
    Toast.makeText(getApplicationContext(),
                    "Please enter your e-mail id", Toast.LENGTH_SHORT)
                    .show();
} else if (!android.util.Patterns.EMAIL_ADDRESS.matcher(
                etMail.getText().toString().trim()).matches()) {
    Toast.makeText(getApplicationContext(),
                    "Please enter valid e-mail id", Toast.LENGTH_SHORT)
                    .show();
}else{
    // Do your stuff
}

编辑:

if (user.getText().toString().trim().equals("")) {
    Toast.makeText(getApplicationContext(),
                    "Please enter username", Toast.LENGTH_SHORT)
                    .show();
} else if (mobile.getText().toString().trim().equals("")) {
    Toast.makeText(getApplicationContext(),
                    "Please enter your mobile number", Toast.LENGTH_SHORT)
                    .show();
} else if (mobile.getText().length() < 10) {
    Toast.makeText(getApplicationContext(),
                    "Please enter valid mobile number", Toast.LENGTH_SHORT)
                    .show();
} else if (!etMail.getText().toString().trim().equals("")) {
    if (!android.util.Patterns.EMAIL_ADDRESS.matcher(
                etMail.getText().toString().trim()).matches()) {
        Toast.makeText(getApplicationContext(),
                    "Please enter valid e-mail id", Toast.LENGTH_SHORT)
                    .show();
    }
}else{
    // Do your stuff
}

快乐编码..

答案 1 :(得分:2)

我已经编辑了你的课程。希望现在有效。

        public class  Login extends BaseActivity {

            JSONObject jsonobject;
            JSONArray jsonarray;

            private ProgressDialog dialog;



            ArrayList<String> arealist;
            //ArrayList<GetterSetter> area;



            public static final String PREFS_NAME = "MyPrefsFile";

            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_login);
                Button login = (Button) findViewById(R.id.button_register);

                login.setOnClickListener(new View.OnClickListener()
                {
                    @Override
                    public void onClick(View v) {

                        EditText user = (EditText) findViewById(R.id.editText_enter_name);
                        EditText mobile = (EditText) findViewById(R.id.editText_mobNo);
                        EditText email = (EditText) findViewById(R.id.editText_email);

                        if (user.getText().toString().trim().equals("")) {
                            Toast.makeText(getApplicationContext(),
                                    "Please enter username", Toast.LENGTH_SHORT)
                                    .show();
                        } else if (mobile.getText().toString().trim().equals("")) {
                            Toast.makeText(getApplicationContext(),
                                    "Please enter your mobile number", Toast.LENGTH_SHORT)
                                    .show();
                        } else if (mobile.getText().length() < 10) {
                            Toast.makeText(getApplicationContext(),
                                    "Please enter valid mobile number", Toast.LENGTH_SHORT)
                                    .show();
                        } else if (!email.getText().toString().trim().equals("")) {
                            if (!android.util.Patterns.EMAIL_ADDRESS.matcher(
                                    email.getText().toString().trim()).matches()) {
                                Toast.makeText(getApplicationContext(),
                                        "Please enter valid e-mail id", Toast.LENGTH_SHORT)
                                        .show();
                            }
                        }else{
                            // Do your stuff
                            PostJson();

                            if (isInternetPresent) {
                                // setting progress bar to zero
                                dialog = new ProgressDialog(Login.this);
                                dialog.setMessage("Please Wait...");
                                dialog.setIndeterminate(false);
                                dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
                                dialog.setProgressNumberFormat(null);
                                dialog.setProgress(0);
                                dialog.show();

        //                          Toast.makeText(Login.this, "Connecting....", Toast.LENGTH_LONG)
        //                                  .show();

                            } else {

                                Toast.makeText(Login.this, "Unable to connect the server, please check your data settings", Toast.LENGTH_LONG)
                                        .show();
                            }
                        }




                    }





                    // =====To check the validation of Emails and Empty
                    // Fields==========//

                    public boolean isEmailValid(Editable email) {
                        boolean isValid = false;

                        String expression = "^(([\\w-]+\\.)+[\\w-]+|([a-zA-Z]{1}|[\\w-]{2,}))@"
                                + "((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?"
                                + "[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\."
                                + "([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?"
                                + "[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|"
                                + "([a-zA-Z]+[\\w-]+\\.)+[a-zA-Z]{2,4})$";
                        CharSequence inputStr = email;

                        Pattern pattern = Pattern.compile(expression,
                                Pattern.CASE_INSENSITIVE);
                        Matcher matcher = pattern.matcher(inputStr);

                        if (matcher.matches()) {
                            isValid = true;
                        }

                        return isValid;
                    }

                    public boolean isMobValid(Editable mobile) {

                        boolean isOk = false;

                        String exp = "^[0-9]{10}$";
                        CharSequence inputStr = mobile;

                        Pattern pattern = Pattern
                                .compile(exp, Pattern.CASE_INSENSITIVE);
                        Matcher matcher = pattern.matcher(inputStr);
                        if (matcher.matches()) {
                            isOk = true;
                        }
                        return isOk;
                    }

                    public boolean validate(EditText[] fields) {
                        // TODO Auto-generated method stub
                        for (int i = 0; i < fields.length; i++) {
                            EditText currentField = fields[i];
                            if (currentField.getText().toString().length() <= 0) {

                                currentField.setError("This field can't be empty");
        //                      Toast.makeText(Login.this, "Enter all the fields..!!!",
        //                              Toast.LENGTH_SHORT).show();
                                return false;
                            }
                        }
                        return true;
                    }
                });
            }

            // ==========//




            // =========================== Json Object==================//

            public void PostJson() {


            }



            @Override
            public void onFailure(Throwable e, String response) {


                Log.e("ERROR_LOG", "onFailure request" + e.toString());
                Toast.makeText(Login.this, "Error in Connection.....",
                        Toast.LENGTH_SHORT).show();

            }

            @Override
            public void onFinish() {
                // //////// { onFinish body}///////////////////////////////
                super.onFinish();


                // ////////////////////////////////////////////////////////

            }
        });
                }


                }

答案 2 :(得分:0)

你需要检查一下:

if (email.getText().toString().equalsIgnoreCase("")) {
    // email is empty
} else {
    //email is not empty
}