Vaadin中的组合框验证器

时间:2012-10-30 16:01:17

标签: java validation combobox vaadin

在文本字段中,我可以查看用户输入的字符数,例如:

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需要什么验证器?

我将非常感谢这些信息。谢谢大家。

2 个答案:

答案 0 :(得分:2)

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

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

因为用户无需等待提交验证,直到他们提交或做任何其他需要与服务器交互的内容。

答案 1 :(得分:1)

我想你应该显式调用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();
    }
}