我使用检票口7.x。我有一个带有两个提交按钮的表单。这两个按钮在提交事件上执行不同的操作,但它们具有相同的字段验证。我在其中一个中覆盖了 AjaxButton onSubmit 以分离不同的行为,但我无法传递到相同的验证方法。
button = new AjaxButton("id",this.getRootForm()) {
@Override
protected void onSubmit(AjaxRequestTarget target, Form<?> form){...}
}
button.setDefaultFormProcessing(false);
@Override
protected void onValidate() {...}
@Override
protected void onSubmit() {...}
我怎样才能通过相同的验证方法和所有表单?
编辑答案
this.getRootForm().add(new IFormValidator() {
@Override
public void validate(Form<?> form) {
doValidate(form);
}
@Override
public FormComponent<?>[] getDependentFormComponents() {
FormComponent<?>[] c = new FormComponent<?>[6];
c[0] = nome;
c[1] = email;
c[2] = cognome;
c[3] = indirizzo;
c[4] = telefono;
c[5] = captcha;
return c;
}
});
protected void doValidate(Form<?> form) {...}
button = new AjaxButton("id",this.getRootForm()) {
@Override
protected void onSubmit(AjaxRequestTarget target, Form<?> form){
doValidate(form);
if (!form.hasError()) {
...
} else{
target.add(feedbackPanel);
}
}
}
button.setDefaultFormProcessing(false);
您可以添加自己的 IFormValidator 来生成和调用您的代码。
创建自己的验证方法。
void doValidate(Form<?> form) {
your validation code here for form.
}
this.getRootForm().add(new IFormValidator() {
void validate(Form<?> form) {
doValidate(form);
}
});
@Override
protected void onValidate() {
doValidate(this);
}
你应该实现IValidator
或IFormValidator
,并在你所有的Form
中使用它。
见 https://ci.apache.org/projects/wicket/guide/8.x/single.html#_form_validation_and_feedback_messages
更新
public class MyValidatingBehavior extends Behavior implements IValidator {
@Override
public void onComponentTag(Component component, ComponentTag tag) {
super.onComponentTag(component, tag);
if (component.hasErrorMessage()) {
tag.append("class", "my-error-style", " ");
}
}
@Override
public void validate(final IValidatable<String> validatable) {
final String candidate = validatable.getValue();
if (!isValid(candidate)) {
validatable.error(new ValidationError(this));
}
}
}