Java电子邮件和密码验证

时间:2016-10-05 21:01:57

标签: java regex

我是java编程的新手,我已经解决了这个问题差不多一个小时了,我不确定为什么我的密码验证会一直说明“Passsword包含空格”&我对电子邮件的验证说明“无效的电子邮件地址”

我多次查看我的代码,但我无法检测到任何错误。任何帮助将不胜感激。

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

1 个答案:

答案 0 :(得分:0)

您需要更改以下电子邮件&amp;密码验证:

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

要,

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

}