Somaru-chan
Somaru-chan

Reputation: 33

Java RegEx for email domain

I try to restrict the email option in my registration form (Android app) to my university's domain only (i.e. ***********@aou.edu.sa or ***********@arabou.edu.sa).

The code I've got so far is this:

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);
            }
        }
    }
}

But every time I try to run the app it crashes at the register activity, due to this particular piece of code.

Any ideas of an alternative and easier way?

Upvotes: 0

Views: 1662

Answers (1)

Nikolas
Nikolas

Reputation: 44398

Give the following regex a try and see the demo Regex101 as well:

^([_A-Za-z0-9-+]+\.?[_A-Za-z0-9-+]+@(aou.edu.sa|arabou.edu.sa))$

The problem was in catching the domain of the email - the part after @. You used [] brackets which define a group dis/allowed characters (depends on the ^) usage. In case you have just a little number of possibilities, you can simply define them between () brackets and separate with | (or) character.

(aou.edu.sa|arabou.edu.sa)

In the regex, I have introduced above, it recognizes an email just with one dot . (as far as I have read from your attempt). You can make a simple change to allow more of the dots.

Edit: Don't forget in Java to escape the dot character with a double slash \\ of course.

Upvotes: 1

Related Questions