SAPUI5 (17) - 数据校验

对用户输入的数据进行校验,是开发过程中不可少的基本要求。sapui5提供了基于数据类型灵活的校验。本篇介绍常用方法。

使用MessageManager校验数据

sap.ui.core.message.MessageManager类有一个registerObject()方法:

registerObject(oObject, bHandleValidation)

第一个参数是ManagedObject对象的实例,第二个参数是boolean类型变量,为true时执行数据校验。这种对数据进行校验的方法简洁方便。举个例子:

		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");

定义一个Integer类型,规定值得范围10000至99999,然后在控件sap.m.Input中使用这个类型。我们通过sap.ui.getCore().getMessageManager()方法得到MessageManager对象,在MessageManager中注册sap.m.Input控件。这样就实现了简单的数据校验。当用户输入的ID不在范围内时,给出提示和错误状态标志。

Integer的校验

attachValidationError()方法

控件都有attachValidationError()方法,用于校验失败时的处理,校验成功有对应的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){
			// 标识控件为错误状态
			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");

当校验失败时,标记控件状态为Error,当校验成功时,标记为成功状态。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对象也可以attachValidationError(), 使用父控件或者core对象的attachValidationError()方法,可以集中处理数据校验。

		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: "长度3至20",
			value: {path: "/productname", type: oStringType}
		});
		
		sap.ui.getCore().attachValidationError(this, function(oEvent){
			// 确定引发错误的ID
			var oElement = oEvent.getParameter("element");
			
			// 标识错误并且提示
			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长度为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对象的attachValidationError()方法及attachValidationError()方法中实现数据校验。因为是集中处理,所以需要找到引发错误的控件,然后根据情况提示不同的错误消息:

			// 确定引发错误的ID
			var oElement = oEvent.getParameter("element");
			
			// 标识错误并且提示
			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长度为3到20!");
			}

使用自定义数据类型实现数据校验

在openui5中使用sap.ui.model.SimpleType.extend()自定义数据类型。在自定义的数据类型中,可以使用formatValue(), parseValue()validateValue()方法,在validateValue()方法中实现自定义的校验规则和提示消息。

		// 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
		});			
		
		// 自定义数据类型
		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");

当自定义的sap.stonetest.productid类型校验不通过时,抛出ValidateException异常。使用该类型的控件通过oEvent.getParameter("message")获取该错误消息。

sap.ui.table.Table数据校验

表格是一种常见的编辑界面,下面给出在sap.ui.table.Table中进行数据校验错误和数据类型转换错误的一个示例。

<!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:"云长", lastName:"关", 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);
    		
    		// 设置core的model使得model对整个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"
    		}));
    		
    		// 第二列:名,长度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: "长度1到15.",
    			label: new sap.ui.commons.Label({text: "名"}),
    			template: new sap.ui.commons.TextField().bindValue({
    				path: "firstName", type: oStringType}),
    			sortProperty: "firstName",
    			filterProperty: "firstName"
    		}));
    		
    		// 第三列:姓,长度1-15
    		oTable.addColumn(new sap.ui.table.Column("last_name", {
    			tooltip: "长度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 + "校验成功."
    					}));

    		});
			
    		// 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 + "校验失败," + 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对象,显示错误消息
    		var oSimpleListBox = new sap.ui.commons.ListBox({
    	 		enabled: true,
    	 		width: "600px",
    	 		height: "200px"
    	 	});
    		
    		// 定义Button对象,清除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>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值