Spring validation field type - spring

I'm writing REST service in Spring, and I would like to have some form validation.
Let's say, that my POJO class has Integer field - age. How to check, if value that came with request is really an Integer? Is there any annotation for that, or should I write some logic for that? I would like to add some comment if validation won't pass in same style like e.g. #NotNull(message = "Product Number cannot be empty.")

Related

Java Bean Validation - Intercepting Validations

I have the following scenario: I am trying to process a form and the model attribute is a bean with String and Long properties. As you all guys know, bean validation offers a lot of annotation to help us determine the validity of the data.
What I am facing is that, for the case of the Long attributes, I can only use #NotNull and another annotation (I dont recall its name) to force the user to enter positive numbers. If the user enters for instance "sdf", the application throws a BIG exception. So what I would like to know is If I can intercept the form processing and validate by my own if the user entered a numeric thing before it explodes (because I cant use #Pattern)... and I cant switch that attribute to String...
Was it clear ?.
Use Spring Custom validation. That is Annotation-based validation and you have the ability to create your own custom validation logic. Spring Custom Validation In this link you can find out more examples and how to use it.

Spring validates controller parameters after conversion. Can it validate before conversion?

Say I have a class Dog with a field, numberOfLegs, validated to be 4 or less.
class Dog {
#Max(4)
int numberOfLegs;
}
This is a parameter to a controller method, and if validation fails, then Spring sends the relevant error message in the response.
However, the request actually sends up a DogRestDto.
class DogRestDto {
#Max(4)
int legs;
}
I use a converter to change this into a Dog for my controller to use, but the validation is done on Dog rather than DogRestDto, and the error message talks about dog.numberOfLegs rather than dog.legs.
Is there a simple way to tell Spring do the validation on the REST dto prior to conversion, so that the error message makes more sense to the client?
I've achieved this by overriding the mvcUriComponentsContributor method in my DelegatingWebMvcConfiguration to replace the RequestResponseBodyMethodProcessor in the requestMappingHandlerAdapter's argumentResolvers with a implementation that validates the REST DTO. It obtains the REST DTO from a request-scoped bean that I've made to hold the source object currently being converted, which is populated by my implementation of the GenericConversionService.
It's not very pretty. I'd love it if Spring gave me a cleaner way to do this.

What is the difference between #Min/#Max validadtion in Controller and in Entity?

I'm creating a SpringBoot MVC Restful web service.
What is the difference between Controller's validation:
Weather getWeather(
#PathVariable #Min(10) #Max(50) Integer temperature)
and Entity's validation:
public class Weather {
#Min(10)
#Max(50)
private final Integer temperature;
Or are its the same?
there is no difference between them at all. the same meaning in both sides.
if you put the validation in a function inside a controller that's mean the validation will be checked only when that function Runs. if an other function Runs and don't have validation of that attribute it will accepte any value because she didn't checked the validation.
and for not repeating the same validation code in many functions. you can use validation annotation inside your entity and put other annotations like #valid... at any function you want it to check the validation constraints.
hope you understand what i want to tell you. and sorry for my english

Spring REST input validation

I'm writing a REST service using Spring Boot and JPA. I need to be able to validate some of the input fields and I want to ensure I'm using a proper pattern for doing so.
Let's assume I have the following model and I also have no control over the model:
{
"company" : "ACME"
"record_id" : "ACME-123"
"pin" : "12345"
"company_name" : ""
"record_type" : 0
"acl" : ['View','Modify']
"language" : "E"
}
The things I need to do are:
Ensure the value is not empty - This seems simple enough using the #NotEmpty annotation and I can pass a message.
Ensure the value is part of a valid list of values - The example here is the language property in the model above. I want the value to be either E,F or S. This seems possible using a custom annotation (eg #ValidValue({"E","F","S"})) but is there a better/"Springy" way to do this?
Ensure the values in a list are part of a valid list of values - The example here is the acl property. Again this seems possible with a custom annotation like #ValidListValues({"View", "Modify", "Delete", "Hide"}) but same question as above.
Set a default value - From what I read, custom validator annotations are only able to validate and not modify. I would like to do something like #DefaultValue(value=5) if the value is null. Is this possible? More on this below.
Set a default value to the return of a static method - For example if the pin field in model above isn't set, I want to set it to something like Util.getRandomDigitsAsString(5).
Use values from another property - I would like to validate that one property contains the string from another property. Using the example model, I want to ensure that record_id starts with company.
I have this setup in what I believe is a standard way with the controller -> service -> DTO -> DAO -> Model. Another option I was thinking about was creating a method in the validateCreate() that would go through all of the items above and throw an exception if needed.
Thanks.
Yes, NotEmpty is the right way
You should define a Language enum. The language field of your POJO should be of type Language
Same as 2. Define an Acl enum.
Define that in your Java code. Initialize the value of the field to 5 by default. If the JSON contains a value, Jackson will set the field value to the value in the JSON. Otherwise, it will stay as 5. Or initialize the field to null, and add a method getValueOrDefault(int defaultValue) that returns the default value you want if the value is null.
Same as 4
Define a custom validator that applies on the class itself, rather than a property of the class. In the validator chec that the two related values are correct.

Analogue of #NotRquired annotation for validation

I use Hibernate Validation 4.3.1.Final and Spring 3.2.0.RELEASE
I have a form with a string attribute. This attribute is not required, but if it contains some value this value should be exactly 10 digits length.
So I need somthing like:
#NotRquired
#Length(min = 10, max = 10)
But there is no annotation like #NotRquired. How I should write validation for this case?
Not that a #NotRquired annotation would not help in this case, because all defined constraints are evaluated. So in the case where the value is not specified #Length would still be validated and fail. There are several things you could do:\
Use the #Pattern constraint and define a pattern which matters the empty string and the one of length 10 characters. Provided of course for not required case you get an empty string
Write a custom constraint, for example #EmptyOrLength which does what you want
Try working with validation groups and assign each constraint to a different group. You then need a way to target the right validation group
Revert to Hibernate Validator specific functionality and use boolean composition of constraints - http://docs.jboss.org/hibernate/stable/validator/reference/en-US/html_single/#d0e3701. You still need a custom constraint though, but you can use a composition of #NotNull and #Length using #ConstraintComposition(OR)

Resources