简体   繁体   中英

Android Email validation with “@”

Is it possible to get an E-Mail validation in my code:

EditText EmailAdresse = (EditText) findViewById(R.id.editTextEMailAdresse);
                        if (EmailAdresse.getText().toString().length() == 0)
                            EmailAdresse.setError("Bitte geben Sie Ihre Email Adresse ein");
                        if ((EmailAdresse.getText().toString().equals(""))) {

At the moment it works withan empty field (Lenght == 0 ) but i want that it works with the @ symbol. If the user does not type anything into the field and it shows please type your Email address. If the user type one letter or symbol in the field he could send an Email. I want that he MUST type "@" into the field and then he could send a mail.

You can use below code for validate email address,

 //Email Pattern    
  public final static Pattern EMAIL_ADDRESS_PATTERN = Pattern.compile("[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{1,256}" + "\\@"
        + "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}" + "(" + "\\." + "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25}" + ")+");

/**
 * Email validation
 * 
 * @param email
 * @return
 */
public static boolean checkEmail(String email) {
    return EMAIL_ADDRESS_PATTERN.matcher(email).matches();
}

You can use this class in your project to validate emails. Code is pretty much self explanatory.

package com.Alok.regex;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class EmailValidator {

    private Pattern pattern;
    private Matcher matcher;

    private static final String EMAIL_PATTERN = 
    "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
    + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";

    public EmailValidator() {
    pattern = Pattern.compile(EMAIL_PATTERN);
}

/**
 * Validate hex with regular expression
 * 
 * @param hex
 *            hex for validation
 * @return true valid hex, false invalid hex
 */
public boolean validate(final String hex) {

    matcher = pattern.matcher(hex);
    return matcher.matches();

     }
 }

You can set expression as per your requirement

 public static boolean isEmailValid(String email) {
    boolean isValid = false;

    String expression = "^[\\w\\.-]+@([\\w\\-]+\\.)+[A-Z]{2,8}$";
    CharSequence inputStr = email;
    Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
    Matcher matcher = pattern.matcher(inputStr);
    if (matcher.matches()) {
        isValid = true;
    }
    return isValid;

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM