Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex validation - show offending character(s). javax.validation

There's regex validation in JSR-303 (javax.validation). For example:

@Pattern(regexp="[\w_\\.]+")
private String username;

The default message shown when the value is not valid (does not match the regex) is something like "Must match {regex}". But users don't understand regex, so it is irrelevant to show it to them. An option is to just show "The username contains illegal characters", and it will probably be fine in most cases. But it will be good to show which character is wrong.

This cannot be directly achieved with regex - it either matches or not. You have to either define other patterns that miss some of the components, or try dropping characters from the string until it matches, and then show these characters to the user.

That was in general. Another question is how to achieve this with javax.validation.

So, to summarize the question:

How to display the offending characters with javax.validation, so that the message looks like "The characters ?, * and $ are illegal"

like image 458
Bozho Avatar asked Apr 07 '11 13:04

Bozho


People also ask

What is /\ S in regex?

The \s metacharacter matches whitespace character. Whitespace characters can be: A space character. A tab character.

What is the regex for special characters?

Special Regex Characters: These characters have special meaning in regex (to be discussed below): . , + , * , ? , ^ , $ , ( , ) , [ , ] , { , } , | , \ . Escape Sequences (\char): To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ).

How do I validate a pattern in regex?

To validate a field with a Regex pattern, click the Must match pattern check box. Next, add the expression you want to validate against. Then add the message your users will see if the validation fails. You can save time for your users by including formatting instructions or examples in the question description.


1 Answers

I would go with a negated version of your validation pattern. So your pattern would just be:

[^\w_\\.]

On validation failure, match that against the input string and output the results to the user.

like image 73
Justin Morgan Avatar answered Oct 20 '22 15:10

Justin Morgan