Spring MVC form validation Date field - java

I have a form field that should be converted to a Date object, as follows:
<form:input path="date" />
And I have requirement to make validation in following way:
If user leaves this field es empty. I need to set some default date.
If User enetered in unacceptable format, I need to present an error.
The problem is that I can meet either 1st or 2nd requirement.
I can register PropertyEditor and in case date is unacceptable set null, and in case this field null set some default date. But with this approach I can't meet 2nd requirement because if I convert it to null I won't have ability to register 2nd error to user.
I can set #DateTimeFormat(pattern="dd-MMM-yyyy") annotation and provide appropriate typeMismatch error but it still return this error when user leaves empty value in this field.
Is any good solution to such problem ?

There is a way to do this if you'll move from Spring MVC validators to Hibernate. It's not a big deal because Hibernate validators work well with Spring Validator interface (also you may be interested in SmartValidator intreface which supports groups).
After that you can specify
#NotNull
annotation on the date field.
In properties file just add
NotNull.[formName].[dateField]=This message will be displayed if no date sent
typeMismatch.[formName].[dateField]=This message will be displayed if spring was not able to convert input to date object (format validation error)
For format check you can use CustomDateEditor.
With this solution you will get expected validation error messages in each case you've specified.

When I have to face such a problem, I reverse the logic. I do not set a default value to an empty field, but I pre-load the field with the default value in the render part of the operation. So I can safely valid with just #DateTimeFormat(pattern="dd-MMM-yyyy") because an empty field suppose that the user indendly removed the default value which is an error.
So IMHO you should set your default values in the GET part of you controller for that form and stick to a simple #DateTimeFormat(pattern="dd-MMM-yyyy") annotation.
I have an application using a #ModelAttribute annotated object containing a date field.
In the object class, the date field is annotated on getter and setter with DateTimeFormat(pattern="dd/MM/yyyy"). And Spring (3.2.4) accept an empty value for the date field which simply sets it to null. So you should use #DateTimeFormat(pattern="dd-MMM-yyyy") and still be able to accept null values.

Related

Beanio : How to validate a field, depending on another field value?

I am parsing a fixed length field flat file to a java bean using beanio library.
I have certain validations provided to number of fields.
For one of the field, I need to add a mandatory validation if another field is having a certain value.
Is there a way to attain this requirement through beanio?

Best practices regarding empty fields and nulls in postgresql

I'm writing a simple webapp to show my coding skills to potential employers. It connects with an API and receives a JSON file which is then deserialized using Jackson and displayed in a table form in the browser. I want to enable the user to persist the Java object in a Postgres database using Hibernate. I got it to work and it does the job nicely but I want to make it more efficient.
Whenever there is no data in the JSON response to put in the object's field (right now all the possible JSON attributes are present in the Java class/Hibernate entity in the form of String fields) I put an empty String ('') and then, with all fields having something and no null objects, it is stored in the database.
Should I only store what I have and put no empty strings in the DB (using nulls instead) or is what I'm doing now the right way?
Null is an absence of a value. An empty string is a value. But that don't impact much to memory. If you want to display data repeatedly and don't want conversion from null to empty string while retrieval you can go for empty string ''.
But if you want unique constraint for values other than empty string '' then use null.
Sometimes null and empty '' can be used to differentiate either data was known or not. for known but not available data use empty and for unknown data null can be used.
Use NULLwhen there isn't a known value.
Never use the empty string.
For example, if you have a customer which didn't supply his address don't say his address is '', say it is NULL. NULL unambiguously states "no value".
For database columns that must have a value for your web application to work, create the backing table with NOT NULL data constraints on those columns.
In your unit tests, call NULL, ..._address_is_null_ and test for success or failure (depending on if the test should trigger no errors or trigger an exception).
The use of '' in databases as a sentinel, a special value that means something other that '', is discouraged. That's because we won't know what you meant it to mean. Also, there might be more than one special case, and if you use '' first, then it makes restructuring more difficult to add others (unless you fall into the really bad practice of using even more special strings to enumerate other special cases, like "deleted" and so on).

Validate bad formatted date in JSON with Jackson

I am currently using the objectMapper of Jackson to serialise values in a JSON and put them in a POJO. I need to validate those values so I use validation annotation such as #Regex, #Max and others.
So what happens for now is that I call objectMapper method to read JSON
publicEnquiry = objectMapper.readValue(jsonNode, Enquiry.class);
Then I retrieve all the validation messages in a list and I return it to the user.
payload = publicEnquiry.getPayload();
Set<ConstraintViolation<Enquiry<payload>>> constraintViolations =
publicEnquiry.getConstraintViolations();
Everything works fine if I send a too big integer, a bad formatted string, or anything that will not create a problem for the serialisation, but if I send a date formatted in an unexpected format, or simply bad formatted like "2010-02" instead of "2010-02-03", then I get a JsonMappingException. It is of course expected because the mapper can't understand a bad-formatted date.
However, I need to manage those exception and to be able to add a validation message each time it happens, in a way that will seem transparent for the user. I need a message like "Validation failed: the expected format is yyyy-MM-dd". And I need to perform the normal validation on the other properties opf the POJO like in a normal case.
Unfortunately, Jackson doesn't offer a method in the objectMapper that would skip the exception-generator fields and give back a list of those troublesome fields, or anything like that. It simply fails if there is a problem.
Does someone would have a solution or at least a suggestion on how to proceed ?

Validating Java objects field-by-field

I'm doing analyses on Java validation.
I need to build a module that validates an object [graph] field-by-field, using annotation and supporting custom domain-driven annotations. The most important aspect is that an invalid object must not be rejected (e.g. by underlying persistence layer) but instead marked as invalid.
For example, pick a class with a number of attributes. If any is invalid (e.g. missing or bad valued) I want to know which one is and mark it in another place as invalid. It is important that I get the name of all the fields that didn't pass validation, whether it's a primitive field or a child entity with a validation problem.
I have taken a look at javax.validation but I couldn't figure out the role of ConstraintViolation: it is returned by the validator when a validation error is found, but AFAIK doesn't show the field name to collect.
The question is: do you have any example of using any implementation of javax.validation that display the list of the field names that are found to be invalid for each validated bean?
Also, can I introduce custom attributes instead of adding a ValidatedBy attribute for each recurring attribute to be validated with custom logic?
If you want the name of the element that caused the ConstraintViolation you must use
Path path = ConstraintViolation.getPropertyPath();
// a path is an iterable of Path.Node objects
// the last node element in the path is the element that caused the violation
// You can get it's name via
Path.Node node = ...;
node.getName();
Take a look at the JSR-303 spec chapter 4.2 for details on the Path.

Multiple field ognl type converter

I have a form with (at the moment) two fields and submit the following:
capture.id = 213
capture.description = DescriptionText
The target object 'capture' is immutable and I would like to provide a type converter to take both values and call the constructor. What I cannot seem to do is get by TypeConverter to be invoked.
If the input is simply:
capture = foo
Then the type converter is called, but obviously this isn't much use, is there away to make a ognl delegate the rest of the rest of the type conversation to me, perhaps passing in a Map of the parameters?
Any ideas? Is this even possible in struts2
versions: struts 2.0.14 & ognl 2.6.11
EDIT: I've done a bit of reading on this and my next attempt seemed to me to be a good plan. My theory was that using the Map syntax would make Ognl convert the values to a map and then call my converter with that map to convert it to my value.
capture[id] = 213
capture[description] = DescriptionText
Nope that doesn't seem make any difference at all.
The way I did this was to have the following in the JSP:
<s:textfield name="capture" value="capture.id" />
<s:textfield name="capture" value="capture.description" />
In the type converter, the String[] values parameter of the convertFromString method will contain both values needed to construct a new immutable capture. Provided that you are consistent with the text field ordering (or better yet, encapsulate it in a tag file), you can use the indexes of the values array to reliably get the appropriate field of the capture object.
The one weird part about this approach is that the convertToString method doesn't really do anything for you. You can return either id or description (or concatenate them together), but since you are using the values attribute in the JSP, it doesn't matter.
It seems the that the answer is no you can't do that with struts2.
I've posted this question on the struts2 mailing list and it seems that it just isn't possible to have multiple fields be presented to a TypeConverter.
The alternative solution suggested is to have mutable object with setters and then have some form of 'petify' method to prevent any future changes.
For my project I've actually implemented another struts Interceptor to implement my custom parameter binding behaviour.

Categories

Resources