Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
Clear All
new posts

    setEditorValueParser and Validation

    Since there does not seem to be a built-in widget for time spans, I am trying to build my own "TimeSpanItem".
    The approach is to use a TextItem as a base and then to fine tune the editor. DateTimeItem or TimeItem are inappropriate as they seem not to be able to deal with ranges of more than 24 hs.
    Here is an example:
    Code:
    class TimeSpanItem extends TextItem{
    
    	public TimeSpanItem(String name, String title) {
    		super(name, title);
    		init();
    	}
    ..
    	
    	private void init(){
    		setEditorValueFormatter( new FormItemValueFormatter() {
    			@Override
    			public String formatValue(Object value, Record record, DynamicForm form, FormItem item) {
    				Integer valueFromRecord = record.getAttributeAsInt(item.getFieldName());
    				if(valueFromRecord != null){
    					int UTCSecs = valueFromRecord;
    					int hours = UTCSecs/60;
    					int minutes = Math.abs(UTCSecs% 60);
    					String retval = hours+":"+NumberFormat.getFormat("00").format(minutes);
    					return retval;
    				} else {
    					return null;
    				}
    			} 
    		});
    		setEditorValueParser(new FormItemValueParser() {
    			@Override
    			public Object parseValue(String value, DynamicForm form, FormItem item) {
    				value = value.trim();
    				String[] split = value.split(":");
    				int retval = 0;
    				try{
    					int hours = Integer.parseInt(split[0]);
    					int minutes = 0;
    					if(split.length > 1){
    						minutes = Integer.parseInt(split[1]);
    						if(hours < 0){
    							minutes *=-1;
    						}
    					}
    					retval = hours*60+minutes;
    				} catch (NumberFormatException e){
    					GWT.warn("Could not interpret "+value);
    				}
    				return retval;
    			}
    		});
    		RegExpValidator timeOffsetValidator = new RegExpValidator();
    		timeOffsetValidator.setExpression("^[0-9]+(:[0-5]?[0-9])?$");
    		setValidators(timeOffsetValidator);
    	}
    }
    It seems, however, that the validation is done after calling the FormItemValueParser, at least values like 0:61 get converted to 1:01.
    As I'd like to rely on a parsable String that passes the Regex validator, I wonder whether there is a way to validate the value in the field before it gets passed to the FormItemValueParser.
    Code:
    setValidateOnExit(true) && 
    setValidateOnChange(true);
    do not seem to help here (validation is still done after the call to the FormItemValueParser).

    Thanks & regards
    fatzopilot
Working...
X