Running a hibernate constraint individually? - java

Is it possible to check a String against a hibernate constraint without having to write a special Class for it? For example, if I just want to check if a given String is an email, is it possible to check it as a one-off test without writing a full class and validating that constraint against a particular property of the class?

You can annotate the property with #Email in your entity class. You can read the documentation in this link: http://docs.jboss.org/ejb3/app-server/HibernateAnnotations/api/org/hibernate/validator/Email.html
Edited:
String email = "email#test.com";
EmailValidator validator = new EmailValidator();
validator.isValid(email, null);
The method "isValid" will return true if your string is a well-formed email address.
Hope it helps!

Related

How to set #NotEmpty annotation messages in Spring?

In a Java (+ Spring Boot) project, there is a notation using javax.validation as shown below:
#NotEmpty(message = "validation.product.notEmpty")
private String product;
#NotEmpty(message = "validation.username.password")
private String password;
I have a look at the usage of them, but there are some points that I could not understand:
1. Is there a special usage e.g. conditional message displaying for validation.username.password? For example if username field is null, then display this message? Or is it completely the same manner as the product field?
2. I search the project, but could not find validation.product.notEmpty or validation.username.password. So, how do they work? I think there should be a definition for these messages, but as I did not find, is it come from default messages of javax.validation?
What is the difference between #EmailRegex and #Email? And is there
any need to also use #NotEmpty with these #EmailRegex or #Email
annotations?
#Email will not throw error for an empty String. So you need #NotEmpty to be sure that this String is not empty if you always require an email to be there.
#Email will consider valid everything that is in the form blabla#blabla.blabla. If you want to further constraint this you can use #EmailRegex so that you allow only blabla#blabla.eu by defining your own regular expression.
#EmailRegex does not seem to be included in hibernate annotations or spring annotations. So it is either a custom annotation imported from somewhere else or just a custom annotation of your application. Inspect the code to see how it actually behaves but from it's name I suppose it behaves as I have explained above.
I search the project, but could not find validation.product.notEmpty
or validation.username.password. So, how do they work? I think there
should be a definition for these messages, but as I did not find, is
it come from default messages of javax.validation?
It should be with {....} so like #NotEmpty(message = "{validation.username.password}") private String password;. In that case Spring will automatically read properties from the property files and apply the value for the property validation.username.password. If it does not exist then go to either application.properties or application.yaml and add that property.
Some more notes on this last one. I have seen some strange cases in backend-frontend applications which might be your case here.
#NotEmpty(message = "validation.username.password")
The actual message thrown here when the validation fails is validation.username.password. I have seen cases where the frontend then reads that message and binds a value to this one. I have seen this to be used when frontend supports multiple languages and binds another value for each language each time. This would explain why you don't have { } or such a property in your application.
#NotEmpty(message = "{validation.username.password}")
with an existing property validation.username.password= password can not be empty
will have as a result when the validation fails the message password can not be empty to be delivered.

Change Java Validator's #Pattern Regex based on input value

I am using Java's Validator class to validate some input fields from my Spring Object class. I am validating URIs, and they can be in either format, http:/myURL/uri, or "readFromURI.v1". Originally, I was just validating the first part, so my Object class had:
#Pattern(regexp="[\\w\\s.,;:*&#(){}+-=?/|!\\[\\]%#$~]{0,512}", message="incorrect format")
private String URI;
Now, if the user selects a checkbox in my app, they will enter in the value as the second format, so I created a new regexp:
#Pattern.List({
#Pattern(regexp="[\\w\\s.,;:*&#(){}+-=?/|!\\[\\]%#$~]{0,512}", message="incorrect format"),
#Pattern(regexp="^\"(Create|Read|Update|Delete)[a-zA-Z]+.*vd+\"${0,512}", message="incorrect format")
})
private String URI;
The regexp is probably wrong for the second part, and I will probably ask that question at a later time. But now whenever I validate either format it fails both conditions. So I'm assuming that the way I wrote it, it's trying to apply both regex's. How can I choose one based on a value? That value field is in the same Class if that helps:
private String URI;
private boolean useHttp; //if true, validate using [\\w\\s.,;:*&#(){}+-=?/|!\\[\\]%#$~]{0,512}
You should write a custom validator, as explained here:
Create a new annotation CustomConstraint annotated with #Constraint(validatedBy = CustomConstraintValidator.class)
Have some class CustomConstraintValidator implements ConstraintValidator<CustomConstraint, YourType>
Annotate YourType with #CustomConstraint
Do your validation in your CustomConstraintValidator depending on your bean value.
Your validation will be able to check whatever field you want to test (I don't remember if class level constraint pass after each field level annotation pass, so you might have to check if URI is not null).

How to use different validation rules on same entity in Hibernate?

Problem:
How to save object Account as nested object when only ID is needed without getting ConstraintValidator exception?
Problem is because i have set validation rules to class, but when i want to save sem entity as nested object i get exception that some property values are missing. So i would liek to have different validation rules when i want to persist object as a whole and when i want to use it only sa nested object (when only ID is needed).
public class Account {
private int id;
#NotNull
private String name;
#NotNull
private String lastName;
#NotNull
private String userName;
//getters&setters
If I include Account as nested object i just need ID to be able to use it as FK (account entity is already in DB), but because of #NotNull annotation i get Exception.
Is there a way to ignore those annotations from Account when trying to save object Shop or how to create different validation rules for Account to validate just soem other properties and not all?
public class Shop {
private int id;
private Account owner; // only ID is needed
Do you have any basic example? I dont understand those in documentation. I have already read documentation before posting here.
You want to look at Bean Validation groups where you can classify specific validations so they are only activated when that group is validated and ignored otherwise.
You can refer to the documentation here for details.
Taking an example from the documentation:
// This is just a stub interface used for tagging validation criteria
public interface DriverChecks {
}
// The model
public class Driver {
#Min(value = 18, message = "You must be 18", groups = DriverChecks.class)
private int age;
// other stuffs
}
A group is nothing more than a tag that allows you to enable/disable validations based on specific use cases at run-time. By not specifying the groups attribute on a bean validation annotation, it defaults to the Default group, which is what Bean Validation uses if a group-tag isn't specified at the time of validation.
That means the following holds true:
// Age won't be validated since we didn't specify DriverChecks.class
validator.validate( driver );
// Age will be validated here because we specify DriverChecks.class
validator.validate( driver, DriverChecks.class );
This works great when you're triggering the validation yourself inside your service methods because you can manually control which group checks are applicable based on that method's use case.
When it comes to integrating directly with Hibernate ORM's event listeners that can also trigger bean validation, group specifications become a bit harder as they must be specified based on the event-type raised by hibernate.
javax.persistence.validation.group.pre-persist
javax.persistence.validation.group.pre-update
javax.persistence.validation.group.pre-remove
For each of the above properties you can specify in the JPA properties supplied to Hibernate, you can list a comma delimited list of groups that are to be validated for each of those event types. This allows you to have varying checks during insert versus update versus removal.
If that isn't sufficient, there is always the fact that you can create your own constraint validator implementation and annotation to plug into Bean Validation and specify that at the class or property level.
I have often found this useful in cases where values from multiple fields must be validated as a cohesive unit to imply their validity as the normal field-by-field validations didn't suffice.

Is there any way to control the order of hibernate validator doing validation?

We have a requirement that every fields of the object must be validated in a special order.
For example, we have Person object like below:
public class Person {
#NotNull
private String firstName;
#NotNull
private String lastName;
// getter and setter
}
When I use the javax.validation.Validator to validate this object, we need to make sure that the firstName always be validated first and then lastName. Is there any way for hibernate validator archive that requirement?
You want to use group sequences. In particular you probably want to redefine the default group for your entity. See also Redefining the Default group for a class as defined by the Bean Validation specification .

Spring MVC 3 Validation annotations - Confirm email

I am trying to validate a form using Spring with integrated JSR-303 validations with Hibernate implementation. I have a "confirm email" (emailConf) field that I would like to confirm is equal to the email field. I saw a post of someone doing it like this:
public class ContactInfoForm {
#NotEmpty
private String name;
#NotEmpty
#Email
private String email;
#Expression(value = "emailConf= email", applyIf = "emailConf is not blank")
private String emailConf;
...
}
However, this emailConf validation is not working (i.e. no error occurs when the fields don't match). I've seen a couple tutorials that have shown similar annotations, but can't find them anymore or any documentation on how this works. Does anyone know a way to validate "confirm email/password" fields through annotation? I am currently using the alternative, which is to implement Validator and validate the confirm fields in the validate method.
May you should have look at this question and its answers: there are many ways discussed how to do a such a validation (it is about password and password confirm, but the problem is the same).
What you need is a "Class-level constraint" (as described by JSR-303) if you want to compare 2 field of the same class. I don't think your #Expression will work that way.

Categories

Resources