Vaadin 7 PasswordField正则验证失效问题求助
Ah, I see the issue here! Let me break down what's going wrong and how to fix it quickly.
The core problem is how Vaadin's RegexpValidator works compared to standard Java regex matching. When you use Matcher.find() in plain Java, it looks for the regex pattern anywhere in the string. But Vaadin's RegexpValidator uses a full-string match by default (it implicitly wraps your regex with ^ and $), and its logic is: the input must match the regex to be valid.
So when you pass "\\s" as the regex, you're telling the validator: "only accept inputs that are entirely a single whitespace character". Any other input (like "abcd" which has no whitespace at all) will fail the validation because it doesn't match the regex—hence why you're seeing the error message no matter what you type.
Fix 1: Use a regex that matches valid (non-whitespace) passwords
Instead of checking for whitespace, write a regex that defines what a valid password looks like: no whitespace anywhere. Use ^\\S+$—this means "from start to end, every character is a non-whitespace character".
Here's the corrected code:
PasswordField field = new PasswordField((String) processConfig.get("name")); field.setWidth("100%"); // Validates that the entire input has no whitespace field.addValidator(new RegexpValidator("^\\S+$", "Whitespace is not allowed for password field"));
Fix 2: Use NegativeRegexpValidator (if your Vaadin version supports it)
If you prefer to explicitly check for whitespace and reject inputs that contain it, use NegativeRegexpValidator. This validator rejects inputs that match the regex (instead of requiring them to match). Just pass "\\s" as the regex, and it will flag any input that contains even one whitespace character.
Code example:
PasswordField field = new PasswordField((String) processConfig.get("name")); field.setWidth("100%"); // Rejects any input that contains whitespace field.addValidator(new NegativeRegexpValidator("\\s", "Whitespace is not allowed for password field"));
A quick note: \\s will match any single whitespace character (space, tab, newline, etc.). If you want to be extra explicit, you could use "\\s+" to match one or more whitespace characters, but either will work for your use case.
内容的提问来源于stack exchange,提问作者masiboo

