【问题标题】:How to validate fields in vaadin made form如何验证 vaadin 表单中的字段
【发布时间】:2015-05-12 13:45:49
【问题描述】:

我正在使用 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){
        //
    }
}

当然,表单除了显示之外什么都不做。 我想做的是,如果不满足某些要求,让 Vaadin 在字段旁边显示错误消息。要求本身并不那么重要(假设我希望电子邮件字段至少包含 8 个字符)。我想知道的是:有没有简单的内置方法可以做到这一点?我到过这里: https://vaadin.com/api/com/vaadin/data/Validator.html

但我不明白如何使用验证器,或者即使那是我想要使用的。我一直在谷歌上寻找使用示例,但到目前为止没有成功。感谢您的帮助!

【问题讨论】:

    标签: java forms validation vaadin vaadin7


    【解决方案1】:

    Vaadin 7

    以下内容适用于 Vaadin 7。 validate() 方法已在 Vaadin 8 中删除。

    Vaadin 中的所有 Field 类型都实现了 Validatable 接口,该接口具有接受 Validator 实现作为参数的 addValidator 方法。

    因此,要添加一个检查 TextField 值长度的验证器,您可以这样做:

    TextField textField = new TextField();
    
            textField.addValidator(
    
                    new StringLengthValidator(
                         "Must be between 2 and 10 characters in length", 2, 10, false));
    

    Vaadin 字段具有向用户显示验证错误的内置功能。默认情况下,该字段将以红色突出显示,并且该字段旁边会出现一个感叹号,将鼠标悬停在该字段上会向用户显示更详细的消息。

    自动验证

    默认情况下,该字段现在将在下一个服务器请求中验证,该请求包含该字段对服务器的更改值。如果该字段设置为“立即”,则当该字段失去焦点时会发生这种情况。如果该字段不是即时的,则在其他一些 UI 操作触发返回服务器的请求时将进行验证。

    显式验证

    有时,您可能希望对何时进行验证以及何时向用户显示验证错误进行更多控制。可以通过将 validationVisible 设置为 false 来禁用自动验证。

    textField.setValidationVisible(false);
    

    当您准备好验证字段时(例如,在按钮单击侦听器中),您可以在 TextField 实例上显式调用 validate(如果它是缓冲字段,您也可以使用 commit())方法来触发验证.如果值无效,validate 将抛出 InvalidValueException。如果您想使用 TextField 组件中包含的验证错误的内置显示,您还必须将 validationVisible 设置回 true

    try {
        textField.validate();
    } catch (Validator.InvalidValueException ex) {
        textField.setValidationVisible(true);
        Notification.show("Invalid value!");
    }
    

    请注意,一旦 validationVisbible 设置回 true,验证将隐式发生,因此如果您想保持对验证的显式控制,您必须记住在下一次请求时将其设置回 false。

    验证消息

    可以从调用validate()commit() 时抛出的Validator.InvalidValueException 实例中提取单独的验证消息。

    try {
        textField.validate();
    } catch (Validator.InvalidValueException ex) {
        for (Validator.InvalidValueException cause: ex.getCauses()) {
            System.err.println(cause.getMessage());
        }
    }
    

    验证器

    验证器实现了验证器接口,Vaadin 附带了几个有用的验证器。查看 API 文档了解更多信息:https://vaadin.com/api/7.4.5/com/vaadin/data/Validator.html

    自定义验证器很容易实现,下面是一个取自Book of 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);
    

    【讨论】:

    • 不幸的是,这似乎不再适用于 Vaadin 8。不再有 .validate() 方法......
    • @StephaneGrenier 对于 Vaadin 8,请参阅 Arundev 的 the Answer
    【解决方案2】:

    Vaadin 8

    使用 Vaadin 8 com.vaadin.data.Binder 可以轻松验证您的字段。请参阅手册中的Binding Data to Forms

    创建一个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();
         }
    }
    

    从 binder 调用 validate() 将调用验证操作。

    beanBinder.validate(); 
    

    验证归档。您可以从页面中的任何位置调用它。我曾经在值更改或单击按钮时调用它。

    【讨论】:

    • 这有助于如何设置和触发验证。但是,它没有回答 OP 关于如何在表单字段旁边显示错误消息的问题。
    • @martin_wun 我们在页面中显示了验证。无论如何,我几乎在 5 年前就开始工作了。那个时候它的工作。你可能有一个新版本。 5 年是一个漫长的差距。
    【解决方案3】:

    问题解决了, 显然我之前看的不够深入。来了:

    field.addValidator(new StringLengthValidator("The name must be 1-10 letters (was {0})",1, 10, true));
    

    这里的所有细节: https://vaadin.com/book/-/page/components.fields.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-05
      • 2016-07-22
      • 2012-08-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多