View Full Version : CustomDateEditor, strange validation ?
fmourioux
Aug 25th, 2004, 02:48 AM
Hi,
I have registered a CustomDateEditor like this :
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
binder.registerCustomEditor(java.util.Date.class, null, new CustomDateEditor(dateFormat,false));
When i put "25/08/04" instead of "25/08/2004" in my field form, the date is ok for the customDateEditor and the date register is in fact : "25/08/0004".
Is there a lenient property to stop the incorrect validation or another way ?
Thanks again,
Fabien.
uze
Aug 25th, 2004, 08:44 AM
To avoid the editor to interpret dates use the following before binding:
dateFormat.setLenient(false);
And it should make it.
Cheers,
Uze
fmourioux
Nov 15th, 2004, 04:02 AM
Hi,
For me it doesn't work ? Someone has the same pb ?
Thanks,
Fabien.
katentim
Nov 16th, 2004, 04:24 AM
Why not use:
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yy");
scqlbw
Mar 9th, 2005, 12:28 AM
Yeah, I meet the same case. Is it a bug.
scqlbw
Mar 9th, 2005, 01:36 AM
I see carefully the source code of CustomDateEditor and find that dateFormat.setLenient(false) doesn't work. I write my own MyCustomDateEditor as such:
import java.beans.PropertyEditorSupport;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.util.StringUtils;
public class MyCustomDateEditor extends PropertyEditorSupport {
private final SimpleDateFormat dateFormat;
private final boolean allowEmpty;
private final boolean strict;
public MyCustomDateEditor(SimpleDateFormat dateFormat, boolean allowEmpty ,boolean strict) {
this.dateFormat = dateFormat;
this.allowEmpty = allowEmpty;
this.strict = strict;
}
public void setAsText(String text) throws IllegalArgumentException {
if (this.allowEmpty && !StringUtils.hasText(text)) {
// treat empty String as null value
setValue(null);
} else {
String pattern = this.dateFormat.toPattern() ;
if ( strict && pattern.length() != text.length() ){
throw new IllegalArgumentException("error date Pattern: " + text + ",should be " + pattern );
}
try {
setValue(this.dateFormat.parse(text));
} catch (ParseException ex) {
throw new IllegalArgumentException("Could not parse date: "
+ ex.getMessage());
}
}
}
public String getAsText() {
return (getValue() == null ? "" : this.dateFormat
.format((Date) getValue()));
}
}
and regist MyCustomDateEditor as such:
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy"); binder.registerCustomEditor(Date.class, null ,new MyCustomDateEditor(dateFormat, true,true))
Then when I input something as "25/08/04" ,it throws binding exption to informat me something wrong.It does work for me.I think it may be help you and suggest spring framework to include it! :)
Powered by vBulletin® Version 4.2.1 Copyright © 2013 vBulletin Solutions, Inc. All rights reserved.