Spring annotation validation - Check for unique on update vs add - spring

I have a POJO named sport with properties sportID, sportName, number of players. Using annotated validation I wrote my own annotation constraint to check if sportName exists in the database already or not. It works great when trying to add a sportName, however if I try to update players without changing the sportName the validation fails as well.
Is there any way to pass in a parameter in annotated validation? For example I would like to pass in sportID to the sportName contraint check so that I can exclude that ID in the db query.
Or is there a better way of doing this? In my controller should I let Spring validate inputs (with #Valid) and then if there are no errors call a validate function to check for business rules?

A better way would be using Validation Groups. (Spring MVC and JSR-303 Validation Groups)
Then you can have the default validation group without the "not exits validator". And have an extra group with the "not exits validator". This would allow you to trigger the "not exits validator" only when you need it. (Unfortunately it is not direct supported in Spring 3.0, there you have to start the validation "by hand")
An other way would be not to implement the validator like a field validator, but more like a class validator. -- Have a look at the different solutions discussed for cross field validation in this Stack Overflow Question. It will give you an idea how to access the id field.

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.

What options are there to do output validation of Jersey resources?

What are my options to do output validation of entities in Jersey? Simple use case would be to validate that a returned User instance doesn't have a certain field set to non-null.
Not sure of the context, it this at runtime, or during unit tests?
Bean Validation is one very popular validation framework.
You can readily use it to validate your input (see #NotNull, #Valid and other bean validation annotations with Jersey) ref : https://jersey.java.net/documentation/latest/bean-validation.html
If you want to validate your output, you can use the bean validation framework also, but you will need to use it manually and handle errors.
just check out one of many tutorials on bean validation : http://java.dzone.com/articles/bean-validation-made-simple

JSF 2 and manual validation with JSR 303 - how to track fields?

I want to use JSR 303 (Hibernate Validator) in my JSF 2 project. However, I have complicated forms and field-level validation is not sufficient. I need to use many #ScriptAssert annotations at class-level of my model and its child beans.
So I want to validate form models manually (inside bean action method for example). But I could not understand how I can preserve which validation message should be shown at which field (as it works automatically when field-level validation is on and processed by JSF).
Also I'll need to specify for some of class-level annotations that their messages are to be shown at specific fields. I do not see a straight way to manage it...
Could you please provide a link to explanations of these questions (or tell me that I am doing something wrong?). I think I fail in googling it because internet is bloating with keywords JSF and validation, sorry.
The most idiomatic way to do that is to create custom Bean Validation validator for your class.
You need to create validation annotiation that you would put at the class level (not field level) and associated with that class validator class.
See for instance:
http://docs.jboss.org/hibernate/validator/4.1/reference/en-US/html/validator-usingvalidator.html (Example "Class level constraint")
How can I validate two or more fields in combination?
Validation inside managed bean is also possible, you can throw in your action methods proper validation exception, but usually it is cumbersome, hard to reuse and mixes business logic code with validation.

Extending JSF validation in application

We are developing a web application based on JSF (v2.0) framework. We need to have custom validations in our application. We decided to extend the JSF validation framework by implementing the Validator class.
So let us say that we have multiple input fields which needs to be validated. These input fields are First Name, Last Name, Email Address. We need the user to enter information in these fields. And email address field will have two validations - Required and isValidEmailAddress.
We should be able to use the custom Required validation in First Name, Last Name and Email Address fields. But each time I want different error messages to be displayed for each field. For example in case of First Name, I want to display First Nameis required. In case ofLast nameI want to displayLast name is required`.
How can I reuse the same Required validation implementation for multiple fields but with different error message? Is it possible to do that in JSF? Could you please let me know?
First of all, you don't need to write your own validation logic for required input in JSF. It's one of the basic amenities provided by the framework itself.
JSF's validation framework is cleanly abstracted from messages related to validation, so the two don't have to depend on each other. Your options:
Each input component has a validatorMessage attribute that allows you specify the text/string that will be displayed to the user on validation error. For your specific use case, JSF has gone one step further to specify the required and requiredMessage attribute for input components; to enforce required input and show messages specifically for required input validation respectively. What this means in your use case is that you don't need to write custom validation logic for required input.
By principle of better design you can configure all your desired validation/conversion error messages in a resource bundle (example here) and reference the entries in the resource bundle within your jsf view.
Implementing the validator interface requires you implement the validate method with the following signature
public void validate(FacesContext ctxt, UIComponent comp, Object value) throws ValidatorException
comp refers to the component being validated from which you can get it's Class, clientId etc. value will provide the submitted value from the component

Spring - data validation

I'm just wondering about data validation in Spring. Spring is offering two (maybe more) validation options. First option is to use Validator interface and create whole validation on my own. Second option is to use annotation validation (JSR 303).
And now I'm really confused :) which validation I should chose. What I need is to check if recieved Data Object is correct (by correct i mean all required fields are filled) and this can be done by JSR 303 validation or by my own validator with "Validator instance". But I also need to check if is this Data Object valid against some database constraints (validator is required to check some data in database, eq. is user with this ID registered or not ...) and this can be done only by my own validator.
I don't know which way should be the best. Combine both or create my own validator ?
I will be thankful for any advice ...
Update (relocated from comments)
Ok, I followed Ryan's example and I think I was successful. I created my own implementation of spring Validator and in this Validator I #Autowire-d javax JSR 303 instance. But there was problem with that injection. I had in my configuration and this piece of code caused some exceptions, because spring did not know which Validator I want to inject. So I removed that code.
At the end I also removed the spring Validator implementation, because I dont know where I can get Errors property, which is required as second parameter in "validate" method :). I'm triggering that validation manually from service layer and I really don't know, where I can obtain that Error object.
BTW Well, I found another solution how to implement that validation. I'm thinking about to extend my validator class by LocalValidatorFactoryBean. LocalValidatorFactoryBean class implementing both Validator interfaces (Spring Validator + JSR 303). But i'm not sure if is this good approach. This approach also require Error object, which I don't know where to find/get.
Update
The Error object is coming from "BindException".
FooObjectVO myObject = new FooObjectVO();
BindException errors = new BindException("fooObject", myObject);
They're not really separate options--more like two available implementations of validation. Since Spring's JSR 303 support also implements its own Validator interface, you don't really have to pick one or the other. You can mix and match the implementations in whatever way makes it easiest to get the job done.
In cases such as this I prefer to combine both. I like to use JSR 303 validation for whatever I can. I supplement it with my own validators.

Resources