我尝试将注册表单(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);
}
}
}
}
但是每次我尝试运行应用程序时,由于这段特殊的代码,它会在注册活动中崩溃。
任何替代和更简单方法的想法?
答案 0 :(得分:1)
尝试使用以下正则表达式,并查看演示Regex101:
^([_A-Za-z0-9-+]+\.?[_A-Za-z0-9-+]+@(aou.edu.sa|arabou.edu.sa))$
问题在于捕捉电子邮件的域名 - @
之后的部分。您使用[]
括号定义了一组dis / allowed字符(取决于^
)用法。如果您只有一些可能性,您可以在()
括号之间定义它们,并用|
(or
)字符分隔。
(aou.edu.sa|arabou.edu.sa)
在上面介绍的正则表达式中,它只识别一个点.
的电子邮件(就我从你的尝试中读到的那样)。您可以进行简单的更改以允许更多的点。
编辑:在Java中忘记用双斜杠\\
来逃避点字符。