|
From: Dmitriy K. <dko...@ru...> - 2004-10-05 02:01:46
|
Juergen,
I was browsing the source for DataBinder and co. and playing with
"required fields" functionality and DataBinder's tests and I've noticed
the following - it's not possible to configure the DataBinder to trim
the unwanted spaces from the required fields. Consider the following
test case:
TestBean alef = new TestBean();
DataBinder binder = new DataBinder(alef, "person");
binder.setRequiredFields(new String[]{"name", "touchy", "date"});
MutablePropertyValues pvs = new MutablePropertyValues();
pvs.addPropertyValue(new PropertyValue("touchy", " "));
pvs.addPropertyValue(new PropertyValue("name", null));
binder.bind(pvs);
BindException ex = binder.getErrors();
assertEquals("Wrong amount of errors", 3, ex.getErrorCount());
This will fail because it will not recognize required "touchy" field as
not being present because it contains spaces. It would really be nice to
control trimming of such "accidentally set spaces" for required fields
so the bind() method could then treat them as "missing required field".
I've added the flag to DataBinder ("trimSpacesInStringFields") and small
piece of logic in DataBinder.bind(PropertyValues):
// check for missing fields
if (this.requiredFields != null) {
for (int i = 0; i < this.requiredFields.length; i++) {
PropertyValue pv =
pvs.getPropertyValue(this.requiredFields[i]);
//This is what I added
* if(this.trimSpacesInStringFields && pv != null &&
pv.getValue() != null && pv.getValue() instanceof String) {
pv = new PropertyValue(pv.getName(),
((String)pv.getValue()).trim());
}*
if (pv == null || "".equals(pv.getValue()) ||
pv.getValue() == null) {
// create field error with code "required"
String field = this.requiredFields[i];
this.errors.addError(
new FieldError(this.errors.getObjectName(),
field, "", true,
this.errors.resolveMessageCodes(MISSING_FIELD_ERROR_CODE, field),
getArgumentsForBindingError(field), "Field
'" + field + "' is required"));
}
}
}
...// the rest is omitted
Then by modifying test case a little, it works perfectly:
TestBean alef = new TestBean();
DataBinder binder = new DataBinder(alef, "person");
binder.setRequiredFields(new String[]{"name", "touchy", "date"});
*//Set the new flag
binder.setTrimSpacesInStringFields(true);*
MutablePropertyValues pvs = new MutablePropertyValues();
pvs.addPropertyValue(new PropertyValue("touchy", " "));
pvs.addPropertyValue(new PropertyValue("name", null));
binder.bind(pvs);
BindException ex = binder.getErrors();
System.out.println(alef.getTouchy().length());
System.out.println(ex);
assertEquals("Wrong amount of errors", 3, ex.getErrorCount());
I think it would be a very handy feature (for us at least), unless I
missed something fundamental.
Thoughts?
Regards,
Dmitriy.
|