I'm trying to validate some fields before persisting them to the database. In particular, I need to k开发者_开发技巧now 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?
\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...)
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?
加载中,请稍侯......
精彩评论