PDA

View Full Version : CheckBoxGroup Validation / Validator



The_Jackal
9 Aug 2010, 6:53 PM
I had to dig a bit to work out how to do CheckBoxGroup validation on blur. I also do it on checkbox value change as this makes the error go away as soon as you check a box (rather an having to click away). Here's my solution:

Hope this is useful for someone,
Carl Pritchett


final CheckBoxGroup group = new CheckBoxGroup();
group.setFieldLabel("Group");
group.setValidator(new CheckBoxGroupValidator());

Listener<BaseEvent> checkBoxValidateListener = new Listener<BaseEvent>()
{
public void handleEvent(BaseEvent be)
{
group.validate();
}
};

// Added a check on Render in case an valid model is supplied
group.addListener(Events.Render, checkBoxValidateListener);

CheckBox a = new CheckBox();
a.addListener(Events.Blur, checkBoxValidateListener);
a.addListener(Events.Change, checkBoxValidateListener);
a.setBoxLabel("a");
formBinding.addFieldBinding(new FieldBinding(a, "aModelProp"));

CheckBox b = new CheckBox();
b.addListener(Events.Blur, checkBoxValidateListener);
b.addListener(Events.Change, checkBoxValidateListener);
b.setBoxLabel("b");
bformBinding.addFieldBinding(new FieldBinding(b, "bModelProp"));

group.add(a);
group.add(b);


and here is the Validator (at least one check box must be checked):


public class CheckBoxGroupValidator implements Validator
{
public String validate(Field<?> field, String value)
{
CheckBoxGroup group = (CheckBoxGroup) field;
if (group.getValue() == null)
{
return "Select at least one option";
}
return null;
}

}


Update - maybe better is an all in once sub class of CheckBoxGroup:


public class ValidatingCheckBoxGroup extends CheckBoxGroup
{
private Listener<BaseEvent> checkBoxValidateListener = new Listener<BaseEvent>()
{
public void handleEvent(BaseEvent be)
{
validate();
}
};

@Override
public void add(Field<?> field)
{
super.add(field);
field.addListener(Events.Blur, checkBoxValidateListener);
field.addListener(Events.Change, checkBoxValidateListener);
}

@Override
protected void onRender(Element target, int index)
{
super.onRender(target, index);
validate();
}
}