在“sap.ui.model.SimpleType.extend”中设置TextField值状态

时间:2015-01-13 05:56:54

标签: javascript sapui5

我正在尝试使用正则表达式为表格中的列添加时间验证。首先我添加了一列,请找到以下代码:

oTableFileContents.addColumn(
    new sap.ui.table.Column("Time")
    .setTemplate(
        new sap.ui.commons.TextField({
            editable:true, 
            valueState : sap.ui.core.ValueState.Error, 
            tooltip:""
        })
        .bindProperty("value","Time",new sap.myproject.Time())
    )
    .setLabel(
        new sap.ui.commons.Label({
            text : "Time"
        })
    )
);

这里,我默认将每个TextField的ValueState设置为" Error"这样每个空白条目都处于错误状态。在分配模型时,我必须将每个有效条目设置为"成功"。为此,我将我的扩展类定义为:

sap.ui.model.SimpleType.extend("sap.myproject.Time", {
    formatValue: function(oValue) {
        var re = /^([0-1]\d):([0-5]\d)\s?(?:AM|PM)?$/i;
        if(oValue!=null){
            if(re.test(oValue)) {
                // this.setEditable(false);    //ERROR
                //this.setValueState(sap.ui.core.ValueState.Success);   //ERROR
                alert("Success");
            }
        }

        return oValue;
    },

    parseValue: function(oValue) {
        return oValue;
    },

    validateValue: function(oValue) {}
});

但是在上面的代码中,我无法将TextField的状态设置为" Success"。可能是我无法引用我的TextField。任何人都可以帮我设置这个Valuestate吗?任何帮助/建议将不胜感激。谢谢,库纳尔。

1 个答案:

答案 0 :(得分:2)

请不要,不要试图从格式化程序中引用UI控件,永远! : - )

简单地抛出sap.ui.model.FormatException,框架将为您完成剩下的工作:

// ...snip...
formatValue: function(oValue) {
    var re = /^([0-1]\d):([0-5]\d)\s?(?:AM|PM)?$/i;
    if(oValue!=null){
        if(!re.test(oValue)) {
            throw new sap.ui.model.FormatException("Value " + oValue + " is not in a valid Date format");
        }
    }
    //optional, if you don't want empty/null dates
    else {
        throw new sap.ui.model.FormatException("Date cannot be null or empty");
    }

    return oValue;
},
// ...snip...

编辑:为了获得格式或验证错误的直观线索,您应该附加到控制器的onInit事件处理程序中的格式和验证事件处理程序:

sap.ui.getCore().attachFormatError(function (oEvent) {
  oEvent.getParameter("element").setValueState(sap.ui.core.ValueState.Error);
});
sap.ui.getCore().attachValidationError(function (oEvent) {
  oEvent.getParameter("element").setValueState(sap.ui.core.ValueState.Error);
});
sap.ui.getCore().attachValidationSuccess(function (oEvent) {
  oEvent.getParameter("element").setValueState(sap.ui.core.ValueState.None);
});