views:

34

answers:

2

I'm trying to validate some fields before persisting them to the database. In particular, I need to know that a String contains a non-whitespace character.

I'm using the javax.validation.constraints.Pattern annotation, as follows:

@Pattern(regexp = "[^\\s]")
private String field;

This seems to throw the ConstraintViolation on every String. What am I missing?

A: 

I think you need "[\\s]+". The + ensures one or more of this character class occurs.


Edit: If I re-read the question, I wonder if you enter Strings like "A dog runs" and it breaks because there are non-whitespace characters, but there are also whitespace characters. Try this:

((\\s+)?([^\\s]))+

Last thing: Not sure why you have a private void field -- was that supposed to be a String?

Andy
Seems plausible, but no, that doesn't change anything.
FarmBoy
`\S` (or its equivalent `[^\s]`) should work according to the docs. Do you think it's putting an automatic `"^" + expr + "$"`? According to the docs it shouldn't, but maybe try `.*\S.*`
Ian Henry
@Ian - That's it. Post as an answer, and I'll upvote and accept.
FarmBoy
+1  A: 

\S (or its equivalent [^\s]) should work according to the docs. Do you think it's putting an automatic "^" + expr + "$"? According to the docs it shouldn't, but maybe try .*\S.*

(from my comment -- thought this answer was a total shot in the dark; got lucky. Those docs could use some revising...)

Ian Henry