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

17,392

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.

Share:
17,392
Bozho
Author by

Bozho

Bozhidar Bozhanov - Senior Java developer (CV | Web CV) Creator of: https://logsentinel.com/ (LogSentinel SIEM) https://logsentinel.com/sentineldb (GDPR-compliant, privacy-by-design datastore) http://computoser.com (algorithmic music generation)

Updated on June 18, 2022

Comments

  • Bozho
    Bozho almost 2 years

    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"

  • Justin Morgan
    Justin Morgan about 13 years
    @Bozho - Don't forget that you'll also need something to make sure the input isn't empty if you do it this way.