java 如何在 Vaadin 8 中添加验证器?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42491883/
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 add Validators in Vaadin 8?
提问by Diego D
In Vaadin 7 there was an addValidator function, but in Vaadin 8 it does not exist.
在 Vaadin 7 中有一个 addValidator 函数,但在 Vaadin 8 中它不存在。
Vaadin 7 Example:
Vaadin 7 示例:
TextField user = new TextField("User:");
user.setRequired(true);
user.setInputPrompt("Your username");
user.addValidator(new NullValidator("Username can't be empty", false));
user.setInvalidAllowed(false);
回答by Diego D
I found the answer here: Whats New
我在这里找到了答案:最新消息
Example:
例子:
new Binder<Person>().forField(tf)
.withValidator(str -> str.length() == 4, "Must be 4 chars")
.withConverter(new StringToIntegerConverter("Must be Integer"))
.withValidator(integer -> integer.equals(2017), "Wrong date")
.bind(Person::getBirthYear, Person::setBirthYear);
回答by Basil Bourque
The accepted Answer by Diego Dlooks correct. That code looks to be taken from this very brief (3 minutes) but veryhelpful video published by the Vaadin company, Type safe validation before and after converters. Shows the new Vaadin 8 approach to validation. I'll add some notes, show expanded syntax, and provide full example code for a full working app.
该迭戈d接受的答案看起来是正确的。该代码看起来取自Vaadin 公司发布的这个非常简短(3 分钟)但非常有用的视频,在转换器之前和之后进行类型安全验证。展示了新的 Vaadin 8 验证方法。我将添加一些注释,显示扩展语法,并提供完整的工作应用程序的完整示例代码。
Validator + Binder
验证器 + 绑定器
One big difference in Vaadin 8 is that validators require the use of a binder. In the old days, you attached a validator to a field, but now in Vaadin 8 you attach a validator only to a binder. The Vaadin team recognizes that for some simple situations this requirement of a binder may prove annoying, but for the most part they sensibly expect situations needing validation are quite likely also doing binding. A very logical re-think, I believe. Discussed in another Vaadin company video, Webinar: What's new in Vaadin 8?.
Vaadin 8 的一大不同是验证器需要使用 binder。在过去,您将验证器附加到字段,但现在在 Vaadin 8 中,您只将验证器附加到活页夹。Vaadin 团队认识到,对于一些简单的情况,这种对绑定器的要求可能会很烦人,但在大多数情况下,他们明智地期望需要验证的情况也很可能进行绑定。我相信这是一个非常合乎逻辑的重新思考。在另一个 Vaadin 公司视频中讨论过,网络研讨会:Vaadin 8 有什么新功能?.
Validation & converters
验证和转换器
We define two different validators, one to be called before a converter converts the user's data-entry and another to be called after conversion. So the order of the fluent-style withValidator
and withConverter
method calls is key to correct behavior here. Of course beforeConversion
and afterConversion
are poor names for validator objects, but are done so to make clear the intent of running before or after converter in this demo.
我们定义了两个不同的验证器,一个在转换器转换用户的数据输入之前调用,另一个在转换后调用。因此,流畅风格withValidator
和withConverter
方法调用的顺序是纠正此处行为的关键。当然beforeConversion
和afterConversion
是验证器对象的糟糕名称,但这样做是为了明确在此演示中在转换器之前或之后运行的意图。
Lambda synax optional
Lambda Synax 可选
One validator uses conventional Java code style overriding a method. The other validator uses Lambda syntax. Watch the video and see the Diego D Answerfor code further simplified with single-line Lambda arguments.
一个验证器使用覆盖方法的传统 Java 代码样式。另一个验证器使用 Lambda 语法。观看视频并查看Diego D Answer,了解使用单行 Lambda 参数进一步简化的代码。
package com.example.valapp;
import com.vaadin.annotations.Theme;
import com.vaadin.annotations.VaadinServletConfiguration;
import com.vaadin.data.Binder;
import com.vaadin.data.ValidationResult;
import com.vaadin.data.Validator;
import com.vaadin.data.ValueContext;
import com.vaadin.data.converter.StringToIntegerConverter;
import com.vaadin.server.VaadinRequest;
import com.vaadin.server.VaadinServlet;
import com.vaadin.ui.*;
import javax.servlet.annotation.WebServlet;
/**
* This UI is the application entry point. A UI may either represent a browser window
* (or tab) or some part of a html page where a Vaadin application is embedded.
* <p>
* The UI is initialized using {@link #init(VaadinRequest)}. This method is intended to be
* overridden to add component to the user interface and initialize non-component functionality.
*/
@Theme ( "mytheme" )
public class MyUI extends UI {
@Override
protected void init ( final VaadinRequest vaadinRequest ) {
final TextField tf = new TextField ( "Enter year of birth:" );
Validator<String> beforeConversion = new Validator < String > ( ) {
@Override
public ValidationResult apply ( String s, ValueContext valueContext ) {
if(s.length ()!= 4) {
return ValidationResult.error ( "Year must consist of 4 digits" );
} else {
return ValidationResult.ok () ;
}
}
} ;
Validator<Integer> afterConversion = Validator.from ( value -> value.equals ( 2017 ), "Wrong year." );
new Binder < Person > ( )
.forField ( tf )
.withValidator ( beforeConversion )
.withConverter ( new StringToIntegerConverter ( "Input must be Integer" ) )
.withValidator ( afterConversion )
.bind ( Person:: getYearOfBirth, Person:: setYearOfBirth );
Button button = new Button ( "Tell me" );
button.addClickListener ( event -> Notification.show("This is the caption", "This is the description", Notification.Type.HUMANIZED_MESSAGE) );
setContent ( new VerticalLayout ( tf , button ) );
}
@WebServlet ( urlPatterns = "/*", name = "MyUIServlet", asyncSupported = true )
@VaadinServletConfiguration ( ui = MyUI.class, productionMode = false )
public static class MyUIServlet extends VaadinServlet {
}
}
回答by Brett Sutton
What if you don't have a binder due to creating a dynamic form?
如果由于创建动态表单而没有活页夹怎么办?
Vaadin 8.1 supports removing the binder for a field which supports dynamic forms. If you make a field invisible then remove the binder for that field. Re-add the binder when you make the field visible.
Vaadin 8.1 支持删除支持动态表单的字段的活页夹。如果您使字段不可见,则删除该字段的活页夹。当您使字段可见时,重新添加活页夹。