Hibernate Books

All times are UTC - 5 hours [ DST ]



Post new topic Reply to topic  [ 4 posts ] 
Author Message
 Post subject: validator: specify format only if not null
PostPosted: Wed May 31, 2017 5:06 pm 
Regular
Regular

Joined: Mon Aug 07, 2006 6:22 pm
Posts: 67
I have a bunch of bean properties that I need to be in a specific format, but only if they are non-null. This will be a common pattern. If I use @Size with min/max, or @Digits, they will fail if the value is null.

What's are some reasonable strategies for facilitating this? I don't want to implement a custom validator for every property, although I could perhaps live with a single validator and annotation like "@OnlyValidateIfNotNull", if it were possible for that to work.


Top
 Profile  
 
 Post subject: Re: validator: specify format only if not null
PostPosted: Wed May 31, 2017 5:31 pm 
Regular
Regular

Joined: Mon Aug 07, 2006 6:22 pm
Posts: 67
Hmm. I guess this is a longstanding issue: https://stackoverflow.com/questions/175 ... s-not-null .

So if I were to implement a "@NullOrSize" validator (and something similar for "Digits" and others), is there anything I can reuse? I see that the "@Size" validator is built-in ("validatedBy" empty). The implementation would be straightforward, but I'd prefer not to write code that I don't have to.


Top
 Profile  
 
 Post subject: Re: validator: specify format only if not null
PostPosted: Wed May 31, 2017 5:50 pm 
Regular
Regular

Joined: Mon Aug 07, 2006 6:22 pm
Posts: 67
Hmm, maybe I should say never mind about the whole issue. It does appear that "@Size" with a min value doesn't fail if the value is null.


Top
 Profile  
 
 Post subject: Re: validator: specify format only if not null
PostPosted: Tue Jun 06, 2017 5:44 am 
Hibernate Team
Hibernate Team

Joined: Sat Jan 24, 2009 12:46 pm
Posts: 388
All the built-in constraints accept null as a valid input (except @NotNull of course), so no custom constraints are needed for that. The idea is that @NotNull should be explicitly added if null is not a valid value.

_________________
Visit my blog at http://musingsofaprogrammingaddict.blogspot.com/


Top
 Profile  
 
Display posts from previous:  Sort by  
Post new topic Reply to topic  [ 4 posts ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.