java 正则表达式验证 - 显示违规字符。javax.validation

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5581852/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 11:46:15  来源:igfitidea点击:

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

javaregexvalidation

提问by Bozho

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

JSR-303 (javax.validation) 中有正则表达式验证。例如:

@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.

当值无效(与正则表达式不匹配)时显示的默认消息类似于“必须匹配 {regex}”。但是用户不理解正则表达式,所以向他们展示它是无关紧要的。一个选项是只显示“用户名包含非法字符”,在大多数情况下可能没问题。但是最好显示哪个字符是错误的。

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.

那是一般的。另一个问题是如何使用 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"

如何使用 javax.validation 显示有问题的字符,使消息看起来像“字符 ?、* 和 $ 是非法的”

采纳答案by Justin Morgan

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.

验证失败时,将其与输入字符串进行匹配并将结果输出给用户。