1

在文本字段中,我可以检查用户输入了多少个字符,例如:

Field field;
field.addValidator(
    new StringLengthValidator(
        "WARNING MESSAGE HERE", 6, 20, false));

如果数字不在范围内,则抛出警告消息。对于数字字段,我可以检查类型:

field.addValidator(new Validator() {

   public boolean isValid(Object value) {
      try {
        float f = Float.parseFloat((String) value);
        return true;
      } catch (Exception e) {
         field.getWindow().showNotification("WARNING MESSAGE HERE");
         field.setValue(0);                            
         return false;
      }
   }

   public void validate(Object value)
      throws InvalidValueException {
   }

});

对于组合框,我指定以下内容:

final ComboBox combobox = new ComboBox("...");

if("someProperty".equals(propertyId)) {
   field = combobox;
}

field.setRequired(true);                
field.setRequiredError("WARNING MESSAGE HERE");                

如果我将其留空,则不会显示警告并将表单发送到服务器。ComboBox 需要什么验证器?

我将非常感谢您提供的信息。谢谢大家。

4

2 回答 2

1

您正在寻找的是用户更改任何内容后立即回调到服务器。

// Fire value changes immediately when the field loses focus
combobox.setImmediate(true);

为此,用户不必等待获得验证,直到他们提交或执行任何其他需要与服务器交互的操作。

于 2012-10-31T09:09:45.687 回答
0

我想你应该显式调用 validate() 方法:

/**
 * Checks the validity of the Validatable by validating the field with all
 * attached validators except when the field is empty. An empty field is
 * invalid if it is required and valid otherwise.
 * 
 * The "required" validation is a built-in validation feature. If the field
 * is required, but empty, validation will throw an EmptyValueException with
 * the error message set with setRequiredError().
 * 
 * @see com.vaadin.data.Validatable#validate()
 */
public void validate() throws Validator.InvalidValueException {

    if (isEmpty()) {
        if (isRequired()) {
            throw new Validator.EmptyValueException(requiredError);
        } else {
            return;
        }
    }

    // If there is no validator, there can not be any errors
    if (validators == null) {
        return;
    }
...

默认情况下,Form 执行验证:

/**
 * Checks the validity of the validatable.
 * 
 * @see com.vaadin.data.Validatable#validate()
 */
@Override
public void validate() throws InvalidValueException {
    super.validate();
    for (final Iterator<Object> i = propertyIds.iterator(); i.hasNext();) {
        (fields.get(i.next())).validate();
    }
}
于 2012-10-30T18:18:31.303 回答