【发布时间】:2018-10-29 17:12:27
【问题描述】:
我尝试将注册表单(Android 应用)中的电子邮件选项限制为仅限我大学的域(即***********@aou.edu.sa 或***********@arabou.edu.sa)。
到目前为止我得到的代码是这样的:
public void validateEmail(EditText anEmail){
//String regex declaration for student emails
String emailPatS = "^[_A-Za-z0-9-+]+(\\.[_A-Za-z0-9-]+)*@" + "[aou.edu.sa]";
//string regex declaration for tutor emails
String emailPatT = "^[_A-Za-z0-9-+]+(\\.[_A-Za-z0-9-]+)*@" + "[arabou.edu.sa]";
//Pattern declaration for student and tutor emails
Pattern studentPat = Pattern.compile(emailPatS);
Pattern tutorPat = Pattern.compile(emailPatT);
//Matcher declaration for student and tutor emails
Matcher studentMatch = studentPat.matcher(anEmail.getText().toString());
Matcher tutorMatch = tutorPat.matcher(anEmail.getText().toString());
//if else for email editText validation
if(studentMatch.matches()){
submitForm();
} else {
//if it doesn't match, first don't allow the user to click sign up button
//then compare to see if it's a tutor's email
signUp.setEnabled(false);
if(tutorMatch.matches()){ //if it does match a tutor's email then allow the user to click sign up and submit the form
signUp.setEnabled(true);
submitForm();
} else { //if it matches neither student nor tutor emails then disallow user to
//click sign up and toast an error message
signUp.setEnabled(false);
anEmail.setError("Please enter your university email only.");
if(regEmail.isInEditMode()){
signUp.setEnabled(true);
}
}
}
}
但每次我尝试运行应用程序时,它都会在注册活动中崩溃,这是由于这段特殊的代码。
有什么更简单的替代方法吗?
【问题讨论】:
-
CRASH 然后添加错误logcat...
-
我不确定您的 reqex 是否正确
String emailPatS = "^[_A-Za-z0-9-+]+(\\.[_A-Za-z0-9-]+)*@" + "[aou.edu.sa]";您是否看到任何以数字开头的电子邮件 ID -
我刚刚又试了一次。它不再崩溃,但电子邮件正则表达式不符合模式并且不会触发错误。
-
您可以使用一个正则表达式同时使用
^[_A-Za-z0-9-+]+(?:\.[_A-Za-z0-9-]+)*@(?:aou\.edu\.sa|arabou\.edu\.sa)$注册学生和导师。见Demo。正如@lexicore 指出的那样,没有完美的电子邮件正则表达式。此正则表达式仅基于您在问题中已有的内容。 -
public void validateEmail(EditText anEmail){ String email = anEmail.getText().toString(); boolean endsWithDomain = email.endsWith("aou.edu.sa"); if(endsWithDomain && Patterns.EMAIL_ADDRESS.matcher(email).matches()) { // 做你想做的 } else { Log.d("App","Email not verify");} }
标签: java android regex string email