java 如何验证 vaadin 表单中的字段
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30192784/
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
How to validate fields in vaadin made form
提问by Jan Ossowski
I am making a Java project with vaadin. Right now I have a user registration form looking like that:
我正在用 vaadin 制作一个 Java 项目。现在我有一个看起来像这样的用户注册表:
public class RegistrationComponent extends CustomComponent implements View {
public static final String VIEW_NAME = "Registration";
public RegistrationComponent(){
Panel panel = new Panel("Registration Form");
panel.setSizeUndefined();
FormLayout content = new FormLayout();
CheckBox checkBox1, checkBox2, checkBox3;
checkBox1 = new CheckBox("Check Box 1");
checkBox2 = new CheckBox("Check Box 2");
checkBox3 = new CheckBox("Check Box 3");
checkBox1.setRequired(true);
checkBox2.setRequired(true);
TextField mailTextField = new TextField("Email Address");
TextField passwordTextField = new TextField("Password");
TextField confirmPasswordTextField = new TextField("Confirm Password");
final Button submitButton = new Button("Submit");
content.addComponent(mailTextField);
content.addComponent(passwordTextField);
content.addComponent(confirmPasswordTextField);
content.addComponent(checkBox1);
content.addComponent(checkBox2);
content.addComponent(checkBox3);
content.addComponent(submitButton);
content.setSizeUndefined(); // Shrink to fit
content.setMargin(true);
panel.setContent(content);
setCompositionRoot(panel);
//listeners:
submitButton.addClickListener(new Button.ClickListener() {
public void buttonClick(Button.ClickEvent event) {
//
}
});
}
@Override
public void enter(ViewChangeListener.ViewChangeEvent event){
//
}
}
Of course, the form doesn't do anything other than being displayed. What I wanna do, is make Vaadin display error messages next to fields if some requirements are not met. The requirements themselves are not that important (lets say I want email field to contain at least 8 characters). What I wanna know, is: is there any simple built-in way to do that? I was here: https://vaadin.com/api/com/vaadin/data/Validator.html
当然,表单除了被显示之外不会做任何事情。我想要做的是,如果不满足某些要求,让 Vaadin 在字段旁边显示错误消息。要求本身并不重要(假设我希望电子邮件字段包含至少 8 个字符)。我想知道的是:有没有简单的内置方法可以做到这一点?我在这里:https: //vaadin.com/api/com/vaadin/data/Validator.html
but I dont understand how to use a validator, or even if that is what I want to use. I've been looking all over google for usage examples, but so far with no success. Thanks for help!
但我不明白如何使用验证器,或者即使这是我想要使用的。我一直在谷歌上寻找使用示例,但到目前为止没有成功。感谢帮助!
回答by Eric
Vaadin 7
瓦丁 7
The following applies to Vaadin 7. The validate() method has been removed in Vaadin 8.
以下内容适用于 Vaadin 7。validate() 方法已在 Vaadin 8 中删除。
All Field types in Vaadin implement the Validatable
interface which has the addValidator
method that accepts an implementation of Validator as parameter.
Vaadin 中的所有 Field 类型都实现了Validatable
接口,该接口具有addValidator
接受 Validator 的实现作为参数的方法。
So to add a validator that checks the length of the value of a TextField, you would do this:
因此,要添加检查 TextField 值长度的验证器,您可以这样做:
TextField textField = new TextField();
textField.addValidator(
new StringLengthValidator(
"Must be between 2 and 10 characters in length", 2, 10, false));
Vaadin fields have built-in functionality for displaying the validation errors to the user. By default, the field will be highlighted in red and an exclamation mark will appear next to the field, hovering over this will show a more detailed message to the user.
Vaadin 字段具有向用户显示验证错误的内置功能。默认情况下,该字段将以红色突出显示,并且该字段旁边会出现一个感叹号,将鼠标悬停在该字段上会向用户显示更详细的消息。
Automatic Validation
自动验证
By default, the field will now validate on the next server request which contains a changed value for the field to the server. If the field is set to 'immediate', this will happen when the field looses focus. If the field is not immediate, validation will happen when some other UI action triggers a request back to the server.
默认情况下,该字段现在将在下一个服务器请求上进行验证,该请求包含该字段到服务器的更改值。如果该字段设置为“立即”,则会在该字段失去焦点时发生这种情况。如果该字段不是即时的,则在其他 UI 操作触发返回服务器的请求时将进行验证。
Explicit Validation
显式验证
Sometimes, you may want to exercise more control over when validation happens and when validation errors are displayed to the user. Automatic validation can be disabled by setting validationVisible
to false.
有时,您可能希望对何时发生验证以及何时向用户显示验证错误进行更多控制。可以通过设置validationVisible
为 false来禁用自动验证。
textField.setValidationVisible(false);
When you are ready to validate the field (e.g. in a button click listener) you can explicitly call the validate
(you can also use commit()
if it is a buffered field) method on the TextField instance to trigger validation. validate
will throw an InvalidValueException
if the value is invalid. If you want to use the builtin display of validation errors included in the TextField component you will also have to set validationVisible
back to true
.
当您准备好验证字段(例如在按钮单击侦听器中)时,您可以显式调用 TextField 实例上的validate
(commit()
如果它是缓冲字段,您也可以使用)方法来触发验证。如果值无效,validate
将抛出一个InvalidValueException
。如果您想使用 TextField 组件中包含的验证错误的内置显示,您还必须validationVisible
将true
.
try {
textField.validate();
} catch (Validator.InvalidValueException ex) {
textField.setValidationVisible(true);
Notification.show("Invalid value!");
}
Note that once validationVisbible is set back to true, validation will happen implicitly so you must remember to set it back to false on the next request if you want to maintain explicit control over validation.
请注意,一旦将validationVisbible 设置回true,验证将隐式发生,因此如果您想保持对验证的显式控制,您必须记住在下一个请求时将其设置回false。
Validation Messages
验证消息
Individual validation messages can be extracted from the instance of Validator.InvalidValueException which is thrown when validate()
or commit()
is called.
可以从 Validator.InvalidValueException 的实例中提取单个验证消息,该实例在调用validate()
或时抛出commit()
。
try {
textField.validate();
} catch (Validator.InvalidValueException ex) {
for (Validator.InvalidValueException cause: ex.getCauses()) {
System.err.println(cause.getMessage());
}
}
Validators
验证器
Validators implement the Validator interface and there are several useful validators shipped with Vaadin. Check out the API docs for more information on these: https://vaadin.com/api/7.4.5/com/vaadin/data/Validator.html
验证器实现了 Validator 接口,并且 Vaadin 附带了几个有用的验证器。查看 API 文档以获取有关这些的更多信息:https: //vaadin.com/api/7.4.5/com/vaadin/data/Validator.html
Custom validators are easy to implement, here is an example taken from the Book of Vaadin:
自定义验证器很容易实现,这里有一个来自Vaadin的例子:
class MyValidator implements Validator {
@Override
public void validate(Object value)
throws InvalidValueException {
if (!(value instanceof String &&
((String)value).equals("hello")))
throw new InvalidValueException("You're impolite");
}
}
final TextField field = new TextField("Say hello");
field.addValidator(new MyValidator());
field.setImmediate(true);
layout.addComponent(field);
回答by Arundev
Vaadin 8
瓦丁 8
Using Vaadin 8 com.vaadin.data.Binder
easily you can validate your fields. See Binding Data to Formsin the manual.
使用 Vaadin 8com.vaadin.data.Binder
可以轻松验证您的字段。请参阅手册中的将数据绑定到表单。
Create a TextField
and a binder to validate the text field.
创建一个TextField
和一个活页夹来验证文本字段。
public class MyPage extends VerticalLayout{
TextField investorCode = new TextField();
Binder<MyBean> beanBinder = new Binder<MyBean>();
//Info : MyBean class contains getter and setter to store values of textField.
public MyPage (){
investorCode.addValueChangeListener(e->valueChange(e));
addComponent(investorCode);
bindToBean();
}
private void bindToBean() {
beanBinder.forField(investorCode)
.asRequired("Field cannot be empty")
.withValidator(investorCode -> investorCode.length() > 0,"Code shold be atleast 1 character long").bind(MyBean::getInvestorCode,MyBean::setInvestorCode);
}
//rest of the code .....
private void valueChange(ValueChangeEvent<String> e) {
beanBinder.validate();
}
}
Call validate() from binder will invoke the validation action.
从 binder 调用 validate() 将调用验证操作。
beanBinder.validate();
to validate the filed. You can call this from anywhere in the page. I used to call this on value change or on a button click.
以验证提交。您可以从页面的任何位置调用它。我曾经在值更改或单击按钮时调用它。
回答by Jan Ossowski
Problem solved, Apparently I wasn't looking deep enough before. Here it comes:
问题解决了,显然我之前看的不够深入。它来了:
field.addValidator(new StringLengthValidator("The name must be 1-10 letters (was {0})",1, 10, true));
all details here: https://vaadin.com/book/-/page/components.fields.html
这里的所有详细信息:https: //vaadin.com/book/-/page/components.fields.html