如何在注册用户之前验证来自 EditText 的电子邮件和密码输入

Posted

技术标签:

【中文标题】如何在注册用户之前验证来自 EditText 的电子邮件和密码输入【英文标题】:How to validate Email & Password input from EditText before registering user 【发布时间】:2017-10-20 10:02:47 【问题描述】:

之前如何验证来自 EditText 的电子邮件和密码输入 正在使用 android Studio 注册用户...

电子邮件:必须包含@符号和其他一般要求密码: 必须 >6 位数。

请修改此代码。 我的代码是...

public class RegisterActivity extends AppCompatActivity implements View.OnClickListener

private Button buttonRegister;
private EditText editTextEmail;
private EditText editTextPassword;
private TextView textViewSignin;

private ProgressDialog progressDialog;

private FirebaseAuth firebaseAuth;

@Override
protected void onCreate(Bundle savedInstanceState) 
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_register);

    firebaseAuth=FirebaseAuth.getInstance();
    if (firebaseAuth.getCurrentUser()!=null)
        //profile activity here
        finish();
        startActivity(new Intent(getApplicationContext(),ProfileActivity.class));
    

    progressDialog = new ProgressDialog(this);

    buttonRegister = (Button)findViewById(R.id.buttonRegister);
    editTextEmail = (EditText)findViewById(R.id.editTextEmail);
    editTextPassword = (EditText)findViewById(R.id.editTextPassword);
    textViewSignin = (TextView)findViewById(R.id.textViewSignin);

    buttonRegister.setOnClickListener(this);
    textViewSignin.setOnClickListener(this);


private void registerUser()
    final String email = editTextEmail.getText().toString().trim();
    String password = editTextPassword.getText().toString().trim();

    //uset cannot go any further without entering password
    if(TextUtils.isEmpty(email))
        //email is empty
        Toast.makeText(this, "Please enter email",Toast.LENGTH_SHORT).show();
        //stopping execution further
        return;
    
    if(TextUtils.isEmpty(password))
        //password is empty
        Toast.makeText(this, "Please enter password",Toast.LENGTH_SHORT).show();
        //stopping execution further
        return;
    

    //if validations are ok
    //we will first show progressbar
    progressDialog.setMessage("Registerating User...");
    progressDialog.show();

    firebaseAuth.createUserWithEmailAndPassword(email, password)
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() 
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) 

                    if(task.isSuccessful())
                        //user is successfully registered. we will start profile activity here
                        FirebaseUser user = firebaseAuth.getCurrentUser();
                        Toast.makeText(RegisterActivity.this, "Authentication success. " + user.getUid(), Toast.LENGTH_SHORT).show();
                        progressDialog.hide();
                        finish();
                        startActivity(new Intent(getApplicationContext(),ProfileActivity.class));
                    
                    else
                        Toast.makeText(RegisterActivity.this, "Could not register. please try again", Toast.LENGTH_SHORT).show();
                        progressDialog.hide();
                    

                
            );


@Override
public void onClick(View v) 
    if (v==buttonRegister)
        registerUser();
    
    if(v==textViewSignin)
        finish();
        startActivity(new Intent(this, LoginActivity.class));
    


【问题讨论】:

在您的 xml 中,将 inputtype 属性添加到 EditText 和密码,使用 'getText().toString()' 以编程方式获取它,然后检查此字符串的长度。 【参考方案1】:

我的朋友试试这个

 String emailAddress = etSignInEmail.getText().toString().trim();
    if (etSignInPassword.getText().toString().length() < 6) 
        etSignInPassword.setError(getString("password minimum contain 6 character"));
        etSignInPassword.requestFocus();
    
    if (etSignInPassword.getText().toString().equals("")) 
        etSignInPassword.setError(getString("please enter password"));
        etSignInPassword.requestFocus();
    
    if (!android.util.Patterns.EMAIL_ADDRESS.matcher(emailAddress).matches()) 
        etSignInEmail.setError(getString("please enter valid email address"));
        etSignInEmail.requestFocus();
    
    if (etSignInEmail.getText().toString().equals("")) 
        etSignInEmail.setError(getString("please enter email address"));
        etSignInEmail.requestFocus();
    
    if (!emailAddress.equals("") &&
        etSignInPassword.getText().toString().length() >= 6 &&
        !etSignInPassword.getText().toString().trim().equals("") &&
        android.util.Patterns.EMAIL_ADDRESS.matcher(emailAddress).matches()) 
       // do  your action
    

【讨论】:

谢谢兄弟,我已经按照你的逻辑编辑了我的代码,现在可以完美运行了……【参考方案2】:
Very easy way
    
    
    
            String email = LogineditTextEmailAddress.getText().toString().trim();
            String pass = LogineditTextPassword.getText().toString();
    
            if (email.isEmpty()) 
                LogineditTextEmailAddress.setError("Enter an email address");
                LogineditTextEmailAddress.requestFocus();
                return;
            
    
            if (!android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) 
                LogineditTextEmailAddress.setError("Enter a valid email address");
                LogineditTextEmailAddress.requestFocus();
                return;
            
    
            //checking the validity of the password
            if (pass.isEmpty()) 
                LogineditTextPassword.setError("Enter a password");
                LogineditTextPassword.requestFocus();
                return;
            
    
            if (pass.length() < 8) 
    
                LogineditTextPassword.setError("Password Length Must be 8 Digits");
                LogineditTextPassword.requestFocus();
                return;
    
    
            

【讨论】:

【参考方案3】:

尝试使用此代码进行电子邮件字段验证和密码验证,并检查密码字段中的至少 8 个字符。

  if (isValidEmail(et_regemail.getText().toString())&&etpass1.getText().toString().length()>7)
      if (validatePassword(etpass1.getText().toString())) 
      Toast.makeText(getApplicationContext(),"Go Ahead".....
      
      else

       Toast.makeText(getApplicationContext(),"InvalidPassword".....
       

else

 Toast.makeText(getApplicationContext(),"Invalid Email".....



public boolean validatePassword(final String password)
    Pattern pattern;
    Matcher matcher;
    final String PASSWORD_PATTERN = "^(?=.*[0-9])(?=.*[A-Z])(?=.* 
    [@#$%^&+=!])(?=\\S+$).4,$";
    pattern = Pattern.compile(PASSWORD_PATTERN);
    matcher = pattern.matcher(password);

    return matcher.matches();


public final static boolean isValidEmail(CharSequence target) 
    if (target == null)
        return false;

    return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();

【讨论】:

【参考方案4】:

你为什么不试试这个。

android.util.Patterns.EMAIL_ADDRES

public static boolean EMailValidation(String emailstring) 
        if (null == emailstring || emailstring.length() == 0) 
            return false;
        
        Pattern emailPattern = Pattern
                .compile("^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
                        + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]2,)$");
        Matcher emailMatcher = emailPattern.matcher(emailstring);
        return emailMatcher.matches();
    

【讨论】:

以上是关于如何在注册用户之前验证来自 EditText 的电子邮件和密码输入的主要内容,如果未能解决你的问题,请参考以下文章

如何在 Android 中验证单选按钮组?

在转到另一个Activity之前,需要editText字段

如何在进入主页之前验证电子邮件

Auth0 - 为啥他们希望用户使用 WebView 而不是从 EditText 获取字符串进行身份验证?

带有肯定按钮并验证自定义 EditText 的 AlertDialog

Authorize.Net 验证信用卡 AIM 和 ARB