简体   繁体   中英

Java email and password validation

I am quite new in java programming, ive tackling this problem for almost an hour and i am unsure why my validation for my password keep stating " Passsword contain space" & and my validation for email states " Invalid Email address"

ive look throughout my codes several times but i am unable to detect any error. Any help would be greatly appreciated.

public boolean validate() {

    if (email == null) {
        message = "no email address set";
        return false;
    }

    if (password == null) {
        message = "no password set";
        return false;
    }

    if (!email.matches("\\w+@\\.\\+")) {
        message = "Invalid Email address";
        return false;
    }

    if (password.length() < 8) {
        message = "Password must be at least 8 characters";
        return false;
    }

    //
    else if (!password.matches("\\w*\\s+\\w*")) {
        message = "Password cannot contain space";
        return false;
    }
    return true;
}

You need to change your below email & password validation:

if (!email.matches("\\w+@\\.\\+")) {
    message = "Invalid Email address";
    return false;
}
// And below
else if (!password.matches("\\w*\\s+\\w*")) {
    message = "Password cannot contain space";
    return false;
}

To,

public static final Pattern VALID_EMAIL_ADDRESS_REGEX = 
        Pattern.compile("^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,6}$", Pattern.CASE_INSENSITIVE);

public boolean validateEmailId(String emailId) {
    Matcher matcher = VALID_EMAIL_ADDRESS_REGEX.matcher(emailId);
    return matcher.find();
}

public boolean validate() {
  //...other conditions as it is

  //Invalid Email address
  if(!validateEmailId(email)){
        message = "Invalid Email address";
        return false;
  }

  //Password cannot contain space
  else if(!Pattern.matches("[^ ]*", password)){
     message = "Password cannot contain space";
     return false;
  }

}

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