I need to validate that user type only English text. So it can be Latin letters with some punctuation symbols. For now I write the following regex:
@NotEmpty
@Pattern(regexp = "^[ \\w \\d \\s \\. \\& \\+ \\- \\, \\! \\@ \\# \\$ \\% \\^ \\* \\( \\) \\; \\\\ \\/ \\| \\< \\> \\\" \\' \\? \\= \\: \\[ \\] ]*$")
private String str;
And it works fine.
But I think about more elegant way: I want to validate that my string contains only ASCII symbols. Can I do it with some special annotation or parameter? Or I need to write my custom validator for that? (can you help me with example in this case).
I want something like:
static CharsetEncoder asciiEncoder = Charset.forName("US-ASCII"); // or "ISO-8859-1" for ISO Latin 1
boolean isValid(String input) {
return asciiEncoder.canEncode(input);
}