SAPUI5 (17) - 數(shù)據(jù)校驗(yàn)

對(duì)用戶輸入的數(shù)據(jù)進(jìn)行校驗(yàn)蠕搜,是開發(fā)過程中不可少的基本要求。sapui5提供了基于數(shù)據(jù)類型靈活的校驗(yàn)。本篇介紹常用方法四濒。

使用MessageManager校驗(yàn)數(shù)據(jù)

sap.ui.core.message.MessageManager類有一個(gè)registerObject()方法:

registerObject(oObject, bHandleValidation)

第一個(gè)參數(shù)是ManagedObject對(duì)象的實(shí)例,第二個(gè)參數(shù)是boolean類型變量职辨,為true時(shí)執(zhí)行數(shù)據(jù)校驗(yàn)盗蟆。這種對(duì)數(shù)據(jù)進(jìn)行校驗(yàn)的方法簡(jiǎn)潔方便。舉個(gè)例子:

        var oModel = new sap.ui.model.json.JSONModel();
        oModel.setData({
            productid: "1"
        });
        sap.ui.getCore().setModel(oModel);  
        
        var oIntType = new sap.ui.model.type.Integer(
            {minIntegerDigits: 5, maxIntegerDigits: 5},
            {minimum:10000, maximum:99999});            
        
        var oInput = new sap.m.Input("product_id", {
            tooltip: "大惺婵恪:10000至99999",
            value: {
                path: "/productid",
                type: oIntType
            }
        });
        
        sap.ui.getCore().getMessageManager().registerObject(oInput, true);          
        
        oInput.placeAt("content");

定義一個(gè)Integer類型喳资,規(guī)定值得范圍10000至99999,然后在控件sap.m.Input中使用這個(gè)類型腾供。我們通過sap.ui.getCore().getMessageManager()方法得到MessageManager對(duì)象仆邓,在MessageManager中注冊(cè)sap.m.Input控件。這樣就實(shí)現(xiàn)了簡(jiǎn)單的數(shù)據(jù)校驗(yàn)伴鳖。當(dāng)用戶輸入的ID不在范圍內(nèi)時(shí)宏赘,給出提示和錯(cuò)誤狀態(tài)標(biāo)志。

Integer的校驗(yàn)

attachValidationError()方法

控件都有attachValidationError()方法黎侈,用于校驗(yàn)失敗時(shí)的處理察署,校驗(yàn)成功有對(duì)應(yīng)的attachValidationSuccess()方法。

        var oModel = new sap.ui.model.json.JSONModel();
        oModel.setData({
            productid: "10000"
        });
        sap.ui.getCore().setModel(oModel);  
        
        var oIntType = new sap.ui.model.type.Integer(
            {minIntegerDigits: 5, maxIntegerDigits: 5},
            {minimum:10000, maximum:99999});            
        
        var oInput = new sap.m.Input("product_id", {
            tooltip: "大芯骸:10000至99999",
            value: {
                path: "/productid",
                type: oIntType
            }
        });
        
        oInput.attachValidationError(this, function(oEvent){
            // 標(biāo)識(shí)控件為錯(cuò)誤狀態(tài)
            this.setValueState(sap.ui.core.ValueState.Error);
            
            // 提示   
            sap.m.MessageToast.show("ID的范圍從10000至99999!");
        });     
        
        oInput.attachValidationSuccess(this, function(oEvent){
            this.setValueState(sap.ui.core.ValueState.Success);
        });     

        oInput.placeAt("content");

當(dāng)校驗(yàn)失敗時(shí)贴汪,標(biāo)記控件狀態(tài)為Error,當(dāng)校驗(yàn)成功時(shí)休吠,標(biāo)記為成功狀態(tài)扳埂。ValueState有如下幾種:

  • sap.ui.core.ValueState.Error
  • sap.ui.core.ValueState.None
  • sap.ui.core.ValueState.Success
  • sap.ui.core.ValueState.Warning

容器控件和sap.ui.core.Core對(duì)象也可以attachValidationError(), 使用父控件或者core對(duì)象的attachValidationError()方法,可以集中處理數(shù)據(jù)校驗(yàn)瘤礁。

        var oModel = new sap.ui.model.json.JSONModel();
        oModel.setData({
            productid: "10000",
            productname: "Micro Projector"
        });
        sap.ui.getCore().setModel(oModel);  
        
        var oIntType = new sap.ui.model.type.Integer(
            {minIntegerDigits: 5, maxIntegerDigits: 5},
            {minimum:10000, maximum:99999});            
        
        var oProductIdInput = new sap.m.Input("product_id", {
            tooltip: "大醒舳:10000至99999",
            value: {path: "/productid", type: oIntType}
        });
        
        var oStringType = new sap.ui.model.type.String(null,{
            minLength:3, maxLength:20
        });
        
        var oProductNameInput = new sap.m.Input("product_name", {
            tooltip: "長(zhǎng)度3至20",
            value: {path: "/productname", type: oStringType}
        });
        
        sap.ui.getCore().attachValidationError(this, function(oEvent){
            // 確定引發(fā)錯(cuò)誤的ID
            var oElement = oEvent.getParameter("element");
            
            // 標(biāo)識(shí)錯(cuò)誤并且提示
            oElement.setValueState(sap.ui.core.ValueState.Error);
            if (oElement.getId() == "product_id"){
                sap.m.MessageToast.show("ID的范圍從10000至99999!");
            }
            
            if (oElement.getId() == "product_name"){
                sap.m.MessageToast.show("produc name長(zhǎng)度為3到20!");
            }
        });     
        
        sap.ui.getCore().attachValidationSuccess(this, function(oEvent){
            var oElement = oEvent.getParameter("element");
            oElement.setValueState(sap.ui.core.ValueState.None);
        });
        
        oProductIdInput.placeAt("area1");
        oProductNameInput.placeAt("area2");

本例在core對(duì)象的attachValidationError()方法及attachValidationError()方法中實(shí)現(xiàn)數(shù)據(jù)校驗(yàn)。因?yàn)槭羌刑幚砉袼迹孕枰业揭l(fā)錯(cuò)誤的控件岩调,然后根據(jù)情況提示不同的錯(cuò)誤消息:

            // 確定引發(fā)錯(cuò)誤的ID
            var oElement = oEvent.getParameter("element");
            
            // 標(biāo)識(shí)錯(cuò)誤并且提示
            oElement.setValueState(sap.ui.core.ValueState.Error);
            if (oElement.getId() == "product_id"){
                sap.m.MessageToast.show("ID的范圍從10000至99999!");
            }
            
            if (oElement.getId() == "product_name"){
                sap.m.MessageToast.show("produc name長(zhǎng)度為3到20!");
            }

使用自定義數(shù)據(jù)類型實(shí)現(xiàn)數(shù)據(jù)校驗(yàn)

在openui5中使用sap.ui.model.SimpleType.extend()自定義數(shù)據(jù)類型。在自定義的數(shù)據(jù)類型中赡盘,可以使用formatValue(), parseValue()validateValue()方法号枕,在validateValue()方法中實(shí)現(xiàn)自定義的校驗(yàn)規(guī)則和提示消息。

        // application data
        var oModel = new sap.ui.model.json.JSONModel();
        oModel.setData({
            productid: "10000",
            productname: "Micro Projector"
        });
        sap.ui.getCore().setModel(oModel);  
        
        var oIntType = new sap.ui.model.type.Integer({  
            minIntegerDigits: 5,
            maxIntegerDigits: 5
            }, {
            minimum:1,
            maximum:99999
        });         
        
        // 自定義數(shù)據(jù)類型
        sap.ui.model.SimpleType.extend("sap.stonetest.productid", {
            // format value
            formatValue: function(sValue, sTargetValue){
                return sValue;
            },
            
            // parse value
            parseValue: function(sValue, sSourceValue){
                return sValue;
            },
            
            // validate value
            validateValue: function(sValue){
                if (sValue < 10000 || sValue > 99999){                  
                    throw new sap.ui.model.ValidateException("prodcut id范圍:10000至99999");  
                }
            }
        });
        
        var oInput = new sap.m.Input("product_id", {
            tooltip: "prodcut id范圍:10000至99999"
        });
        
        oInput.bindProperty("value",{
            path: "/productid",
            type: new sap.stonetest.productid()
        });     
        
        oInput.attachValidationError(this, function(oEvent){
            sap.m.MessageToast.show(oEvent.getParameter("message"));
        });
        
        oInput.placeAt("content");

當(dāng)自定義的sap.stonetest.productid類型校驗(yàn)不通過時(shí)陨享,拋出ValidateException異常葱淳。使用該類型的控件通過oEvent.getParameter("message")獲取該錯(cuò)誤消息钝腺。

sap.ui.table.Table數(shù)據(jù)校驗(yàn)

表格是一種常見的編輯界面,下面給出在sap.ui.table.Table中進(jìn)行數(shù)據(jù)校驗(yàn)錯(cuò)誤和數(shù)據(jù)類型轉(zhuǎn)換錯(cuò)誤的一個(gè)示例赞厕。

<!DOCTYPE HTML>
<html>
    <head>
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta http-equiv='Content-Type' content='text/html;charset=UTF-8'/>

        <script src="resources/sap-ui-core.js"
                id="sap-ui-bootstrap"
                data-sap-ui-libs="sap.m, sap.ui.layout, sap.ui.commons, sap.ui.table"
                data-sap-ui-theme="sap_bluecrystal">
        </script>

        <script>        
        
        var oCore = sap.ui.getCore();
        
        oCore.attachInitEvent(function() {
            
            // application data
            var oAppData = {
                    employees:[
                        {firstName:"孟德", lastName:"曹", id: "1", salary : 2169.50},
                        {firstName:"云長(zhǎng)", lastName:"關(guān)", id: "2", salary : 2622.00},
                        {firstName:"飛", lastName:"張", id: "3", salary : 1322.03},
                        {firstName:"孔明", lastName:"諸葛", id: "4", salary : 3522.35},
                        {firstName:"備", lastName:"劉", id: "5", salary : 3732.57}
                    ]
            };
            var oModel = new sap.ui.model.json.JSONModel();
            oModel.setData(oAppData);
            
            // 設(shè)置core的model使得model對(duì)整個(gè)application可見
            sap.ui.getCore().setModel(oModel);          
            
            var oTable = new sap.ui.table.Table({visibleRowCount: 5});
            
            // 第一列:ID
            oTable.addColumn(new sap.ui.table.Column("id", {
                label: new sap.ui.commons.Label({text: "ID"}),
                template: new sap.ui.commons.TextField({value:"{id}"}),
                sortProperty: "id",
                filterProperty: "id"
            }));
            
            // 第二列:名艳狐,長(zhǎng)度1-15
            var oStringType = new sap.ui.model.type.String(null, {
                minLength : 1,
                maxLength : 15
            });
            oTable.addColumn(new sap.ui.table.Column("first_name", {
                tooltip: "長(zhǎng)度1到15.",
                label: new sap.ui.commons.Label({text: "名"}),
                template: new sap.ui.commons.TextField().bindValue({
                    path: "firstName", type: oStringType}),
                sortProperty: "firstName",
                filterProperty: "firstName"
            }));
            
            // 第三列:姓,長(zhǎng)度1-15
            oTable.addColumn(new sap.ui.table.Column("last_name", {
                tooltip: "長(zhǎng)度1到15.",
                label: new sap.ui.commons.Label({text: "姓"}),
                template: new sap.ui.commons.TextField().bindValue({
                    path: "lastName", type: oStringType}),
                sortProperty: "lastName",
                filterProperty: "lastName"
            }));
            
            // 第四列:salary
            var oFloatType = new sap.ui.model.type.Float("salary", {
                minFractionDigits : 2,
                maxFractionDigits : 2
            }, {
                maximum : 8000
            });
            oTable.addColumn(new sap.ui.table.Column({
                tooltip: "最大值8000",
                label: new sap.ui.commons.Label({text: "薪資"}),
                template: new sap.ui.commons.TextField().bindValue({
                    path: "salary", type: oFloatType}),
                sortProperty: "salary",
                filterProperty: "salary"
            }));        

            // validation success
            oTable.attachValidationSuccess(this, function(oEvent){
                var oElement = oEvent.getParameter('element');
                var sId = oElement.getId();
                oSimpleListBox.addItem(
                        new sap.ui.core.ListItem({
                            text: sId + "校驗(yàn)成功."
                        }));

            });
            
            // validation error
            oTable.attachValidationError(this, function(oEvent){
                var oElement = oEvent.getParameter('element');
                var sId = oElement.getId();
                oSimpleListBox.addItem(new sap.ui.core.ListItem({
                    text: sId + "校驗(yàn)失敗皿桑," + oEvent.getParameter("message")}));                
            });
            
            // parse error
            oTable.attachParseError(this, function(oEvent){
                var oElement = oEvent.getParameter('element');
                var sId = oElement.getId();
                oSimpleListBox.addItem(new sap.ui.core.ListItem({
                    text: sId + "," + oEvent.getParameter("message")}));
            });

            oTable.bindRows("/employees");
            
            // 定義ListBox對(duì)象僵驰,顯示錯(cuò)誤消息
            var oSimpleListBox = new sap.ui.commons.ListBox({
                enabled: true,
                width: "600px",
                height: "200px"
            });
            
            // 定義Button對(duì)象,清除ListBox消息
            var oBtn = new sap.ui.commons.Button({text: "清除消息", press: function(){
                oSimpleListBox.removeAllItems();
            }});
            

            var oLayout = new sap.ui.layout.VerticalLayout({
                content: [oTable, oSimpleListBox, oBtn]
            });
            
            oLayout.placeAt("layoutArea");
        });         
                
            
        </script>

    </head>
    <body class="sapUiBody sapUiResponsiveMargin" role="application">
        <div id="header"></div>
        <div id="layoutArea"></div>
    </body>
</html>
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末唁毒,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子星爪,更是在濱河造成了極大的恐慌浆西,老刑警劉巖,帶你破解...
    沈念sama閱讀 217,542評(píng)論 6 504
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件顽腾,死亡現(xiàn)場(chǎng)離奇詭異近零,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)抄肖,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,822評(píng)論 3 394
  • 文/潘曉璐 我一進(jìn)店門久信,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人漓摩,你說我怎么就攤上這事裙士。” “怎么了管毙?”我有些...
    開封第一講書人閱讀 163,912評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵腿椎,是天一觀的道長(zhǎng)。 經(jīng)常有香客問我夭咬,道長(zhǎng)啃炸,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,449評(píng)論 1 293
  • 正文 為了忘掉前任卓舵,我火速辦了婚禮南用,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘掏湾。我一直安慰自己裹虫,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,500評(píng)論 6 392
  • 文/花漫 我一把揭開白布融击。 她就那樣靜靜地躺著恒界,像睡著了一般。 火紅的嫁衣襯著肌膚如雪砚嘴。 梳的紋絲不亂的頭發(fā)上十酣,一...
    開封第一講書人閱讀 51,370評(píng)論 1 302
  • 那天涩拙,我揣著相機(jī)與錄音,去河邊找鬼耸采。 笑死兴泥,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的虾宇。 我是一名探鬼主播搓彻,決...
    沈念sama閱讀 40,193評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼嘱朽!你這毒婦竟也來了旭贬?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,074評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤搪泳,失蹤者是張志新(化名)和其女友劉穎稀轨,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體岸军,經(jīng)...
    沈念sama閱讀 45,505評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡奋刽,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,722評(píng)論 3 335
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了艰赞。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片佣谐。...
    茶點(diǎn)故事閱讀 39,841評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖方妖,靈堂內(nèi)的尸體忽然破棺而出狭魂,到底是詐尸還是另有隱情,我是刑警寧澤党觅,帶...
    沈念sama閱讀 35,569評(píng)論 5 345
  • 正文 年R本政府宣布趁蕊,位于F島的核電站,受9級(jí)特大地震影響仔役,放射性物質(zhì)發(fā)生泄漏掷伙。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,168評(píng)論 3 328
  • 文/蒙蒙 一又兵、第九天 我趴在偏房一處隱蔽的房頂上張望任柜。 院中可真熱鬧,春花似錦沛厨、人聲如沸宙地。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,783評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽宅粥。三九已至,卻和暖如春电谣,著一層夾襖步出監(jiān)牢的瞬間秽梅,已是汗流浹背抹蚀。 一陣腳步聲響...
    開封第一講書人閱讀 32,918評(píng)論 1 269
  • 我被黑心中介騙來泰國(guó)打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留企垦,地道東北人环壤。 一個(gè)月前我還...
    沈念sama閱讀 47,962評(píng)論 2 370
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像钞诡,于是被迫代替她去往敵國(guó)和親郑现。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,781評(píng)論 2 354

推薦閱讀更多精彩內(nèi)容