我已创建此User
课程:
@Entity
public class User extends Model {
@Id
@Constraints.Email
public String email;
@Constraints.MinLength(3)
@Constraints.MaxLength(255)
public String firstName;
@Constraints.MinLength(3)
@Constraints.MaxLength(255)
public String lastName;
@Constraints.MinLength(3)
@Constraints.MaxLength(255)
public String username;
@Constraints.MinLength(16)
@Constraints.MaxLength(255)
public String password;
public static Finder<String, User> finder = new Finder<>(User.class);
public static User create(User user){
user.password = BCrypt.hashpw(user.password, BCrypt.gensalt(12));
user.save();
return user;
}
...
}
我注意到我可以保存空 User
。这意味着,如果没有email
,则此用户将保留在我的数据库中。
@Test
public void createEmptyUser(){
User user = new User();
user.email="";
user.save();
assertTrue(user.email.isEmpty());
assertNotNull(User.finder.byId(user.email));
assertEquals(true, User.findByEmail(user.email).isPresent());
}
为什么我的考试通过?
答案 0 :(得分:0)
正如我在此处https://github.com/playframework/playframework/blob/master/framework/src/play-java-forms/src/main/java/play/data/validation/Constraints.java所见,isValid
类的EmailValidator
方法如果其agrument为空字符串则返回true:
public static class EmailValidator extends Validator<String> implements ConstraintValidator<Email, String> {
public boolean isValid(String object) {
if(object == null || object.length() == 0) {
return true;
}
return regex.matcher(object).matches();
}
}
考虑将@Constraints.Required
和@Formats.NonEmpty
添加到此验证中。此外,您可以看到MinLength
和MaxLength
验证程序的行为方式相同。