Eric Wilson
Eric Wilson

Reputation: 59365

Regex / javax.validation help -- verifying non-whitespace present -- Java

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?

Upvotes: 3

Views: 3702

Answers (2)

Ian Henry
Ian Henry

Reputation: 22403

\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...)

Upvotes: 2

Andy
Andy

Reputation: 14194

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?

Upvotes: 0

Related Questions