Hello!

See annotations in Java EE. When testing a simple program, what should be removed with a successful test is not displayed in the EmailValidator class!

What could be the problem? I would be happy with the options for the new code / fixed code!

 @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) @Constraint(validatedBy = {EmailValidation.EmailValidator.class}) public @interface EmailValidation { String regularExpression() default "^[_A-Za-z0-9-\\\\+]+(\\\\.[_A-Za-z0-9-]+)*@\"\n" + "\t\t+ \"[A-Za-z0-9-]+(\\\\.[A-Za-z0-9]+)*(\\\\.[A-Za-z]{2,})$"; String message() default "Wrong input"; class EmailValidator implements ConstraintValidator<EmailValidation,User>{ private static String regEX; private static String message; private static String emailField; public void initialize(EmailValidation email) { regEX = email.regularExpression(); message = email.message(); emailField = User.getEmail(); } public boolean isValid(User user, ConstraintValidatorContext constraintValidatorContext) { return emailValidation(user); } private boolean emailValidation(User user){ if(!(emailField.matches(regEX))){ System.out.print("Checking"); System.out.print(message); return false; } System.out.print("AllMatches"); return true; } } 

================================================= =======================

 public class ApplTest { public static void main(String [] string){ User user = new User("Aleksey","13224","Aleksey.Alekseev88@gmail.com"); } } 

================================================= =======================

 public class User { public static String getUserName() { return userName; } public static String getPassword() { return password; } public static String getEmail() { return email; } public User(String userName, String password, String email) { setUserName(userName); setEmail(email); setPassword(password); } private static void setUserName(String userName) { User.userName = userName; } private static void setPassword(String password) { User.password = password; } private static void setEmail(String email) { User.email = email; } private static String userName; private static String password; @EmailValidation // Не работает! private static String email; 

}

  • Derived , well, for the sake of all saint - etki

1 answer 1

Annotations do not work by themselves. You need to skip the class through a handler that understands this kind of annotations. For validation javax.validation.Validator used. But this is an interface, you need to get a specific implementation through a factory, for example:

 ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory(); Validator validator = validatorFactory.getValidator(); 

Now you can use the validator for validation and get a list of all violations:

 User user = new User(...); Set<ConstraintViolation<User>> constraintViolations = validator.validate(user); for (ConstraintViolation<User> cv : constraintViolations) { System.out.println(cv.getMessage()); } 

And further. What is the meaning of validating a static field? (I don’t even know if she works for them in principle?)

P.S.
To use validation in a java se application, you must connect one of the validation libraries to the project. When connecting, follow the instructions of the library supplier in order not to miss the dependencies of the library itself. Here's an example hibernate-validator. In addition to the hibernate-validator itself, you need to add three more artifacts according to the instructions http://hibernate.org/validator/documentation/getting-started/ .

Well, the validator from the question must also be corrected, because in this form, in principle, it is not working.
This worker, with the exception of the regular expression, which did not even try to edit:

 @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) @Constraint(validatedBy = {EmailValidation.EmailValidator.class}) public @interface EmailValidation { String regularExpression() default "^[_A-Za-z0-9-\\\\+]+(\\\\.[_A-Za-z0-9-]+)*@\"\n" + "\t\t+ \"[A-Za-z0-9-]+(\\\\.[A-Za-z0-9]+)*(\\\\.[A-Za-z]{2,})$"; String message() default "Wrong input"; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; // Эти два Class-а вверху нужны для чего-то, без них не запускается // // class EmailValidator implements ConstraintValidator<EmailValidation,User> // Если аннотация планируется применяться к String, то при чём тут User? // public static class EmailValidator implements ConstraintValidator<EmailValidation, String> { private String regEX; private String message; public EmailValidator() { } @Override public void initialize(EmailValidation a) { regEX = a.regularExpression(); message = a.message(); } @Override public boolean isValid(String t, ConstraintValidatorContext cvc) { System.out.println("Checking..."); if (t != null && !(t.matches(regEX))) { System.out.println(message); return false; } System.out.println("Valid input"); return true; } } } 
  • People are calm here is not an experienced person, errors are allowed. Thanks for the referral! - Maks.Burkov
  • Thanks, I'll try! - Maks.Burkov
  • The meaning of the added elements in the annotation is not clear. What do they change in my case? - Maks.Burkov
  • @ Maks.Burkov Just the program did not start, cursing the absence of these elements. What are they for you can read in the literature. I did not read :) - Sergey