Skip to Content
Author's profile photo Former Member

Custom Data Types in SAPUI5

credit card.png

What’s in this blog post…

Data Types

Data types in SAPUI5 are used as a mechanism to validate user input (“hello” isn’t an acceptable value for order quantity, for example) and also to ensure      that data is formatted and displayed appropriately on the UI (like displaying 1234567 as 1,234,567 where required). When used in conjunction with a data model that supports 2-way binding – which is the best way to use them – data types ensure that the data in the model gets updated only if the user provides a valid value.

User input validation can also be done by writing validation logic in event handlers for every single input fields; and formatting displayed values can be done by writing and using formatters wherever values are displayed. As you can already guess though however, this does not scale well and the effort required to maintain a development done with this approach would quickly get high as the application grows.

The SAPUI5 framework comes with some commonly needed data types that can be used in applications. These include Boolean, Date and Float. The behaviour of bindings that use data types can be tweaked by specifying constraints and format options. Constraints (like minimum and maximum for Float) can be used to restrict the range of values that are considered valid. Any user input that violates a constraint is considered to be invalid input, and the corresponding path in the model will not be updated. Format options on the other hand, are specified to configure how a particular value should be displayed on the UI (like groupingSeparator and decimalSeparator for Float). The value at the corresponding path in the model is formatted according to the type’s format options before being displayed. Additionally, the user is also able to enter inputs either with (like 12,345) or without formatting (12345) – and both of these are considered valid.

Screen Shot 2016-06-02 at 12.29.01 pm.png

Custom Data Types

For most requirements, using standard data types (sap.ui.model.type.*) with suitable constraints and format options will suffice. But there can be some requirements (like the example we’ll be working on later in this post) which cannot be satisfied with constraints on standard data types. In these cases, we will need to develop our own data types. We will now look at what all goes into creating a custom data type, along with an example – A custom data type for handling credit card numbers.

To get started with creating a custom data type, we extend the sap.ui.model.SimpleType class and override 3 methods defined in the SimpleType parent class – parseValue, validateValue and formatValue

Screen Shot 2016-06-01 at 8.58.15 pm.png

parseValue(sExternalValue)

This method receives the user’s input as a parameter. This method’s job is to convert the user’s value (external value) into a suitable internal representation of the value (internal value). In our credit card number example, one possible implementation would be to convert the user’s input “4556-2364-5346-4444” into an internal representation without the hyphens “4556236453464444”. The use of doing this becomes obvious when we start implementing one of our other 2 methods – validateValue


validateValue(sInternalValue)

This method receives the parsed value (that is, the internal representation of the value as determined by the parseValue method) and must decide whether or not the value is valid. If the input is determined to be invalid, an exception of type sap.ui.model.ValidateException should be thrown from within this method.

formatValue(sInternalValue)

This method receives the parsed value (internal value) as a parameter and must return a formatted value (that is, a corresponding external value). This formatted value is displayed on the UI.

Before we start implementing our custom data type, let’s have a quick look at when exactly the framework calls each of these 3 methods. We see from the diagram, that the order in which these 3 methods are triggered by the framework is parseValue() -> validateValue() -> formatValue().

CustomTypesBlogPost.png

The ‘Credit card number’ custom data type

parseValue(sExternalValue)

For our example, we’ll just remove any hyphens that are present in the user input using a regular expression, and return the result as the parsed value (as a string of digits). To indicate to the framework that input could not be parsed (for example, trying to parse the string “hello” to a date), throw an exception of type sap.ui.model.ParseException – we don’t do this in our example though.

Screen Shot 2016-06-01 at 9.05.40 pm.png

validateValue(sInternalValue)

For validating whether we’re dealing with a valid credit card number or not, we will implement the Luhn’s algorithm in our validateValue method. To tell the framework that validation failed, we raise a sap.ui.model.ValidateException near the end of the method.

Screen Shot 2016-06-01 at 9.22.52 pm.png

formatValue(sInternalValue)

To format the internal value that we obtained via our parseValue method (which is a string of 16 digits), we add a hyphen after every 4 digits and return the new string from this method (so “1234123412341234” becomes “1234-1234-1234-1234”). This value is then set for the ‘value’ property of our input field, and is visible on the UI.

Screen Shot 2016-06-01 at 9.40.17 pm.png

XML Binding

With our custom data type now ready, we go ahead and bind our input field to a path in our JSONModel (you can use it with other model types too though) and specify a type for the property binding.

Screen Shot 2016-06-02 at 11.52.25 am.png

Controller

Let’s wire in the MessageManager and ask it to do the magic of actually showing the error message to the user for us. This is documented in the UI5 Demokit (OpenUI5 SDK – Demo Kit)

Screen Shot 2016-09-16 at 4.39.43 pm.png

The Result (click on the image if you don’t see it animated)

/wp-content/uploads/2016/09/custom_data_type_966312.gif

CC_invalid.gif

Do you have any feedback on this post? Or a discussion around it that you’d like to start? Go ahead and drop a comment. 🙂

Assigned Tags

      11 Comments
      You must be Logged on to comment or reply to a post.
      Author's profile photo Sergio Guerrero
      Sergio Guerrero

      thanks for sharing this blog Pritin, also, it adds a lot of value to add the Luhn's reference because I think some people that have not dealt with these rules know the background of how CC gets validated, and also it depends on the type of CC which values are considered correct or incorrect.

       

      I also like the part where you included the MessageManager into your blog - nice addition there. Great share!

      Author's profile photo Christopher Solomon
      Christopher Solomon

      Very nice! I like when someone goes into the finer details on a specific subject that is often "glossed over" in the normal material. Thanks and keep blogging!

      Author's profile photo Krishna Kishor Kammaje
      Krishna Kishor Kammaje

      Wonderful post. Thanks a lot for sharing this. I miss the rating option here. Definitely a five star blog.

      Author's profile photo balaji kiran
      balaji kiran

      Its really Wonderful post. Thank you very much Former Member

      Author's profile photo Abhishek Modi
      Abhishek Modi

      This is a really great post and explains the custom data type very well. How do we use i18n text for displaying the validation message? i18n model is not accessible inside the custom data validatevalue function.

      Author's profile photo Steffen Retz
      Steffen Retz

      You can register the i18n-Model using the follwing line of code.

      sap.ui.getCore().setModel(oI18n, "i18n") ;

      I would suggest to do this in a early hook like the onInit-Method of App.controller.js.

      Now you're able to use the i18n-Model inside of your custom type like this:

      var oBundle = sap.ui.getCore().getModel("i18n");
      var sMessageNumberRange = oBundle.getText("YOUR_NUMBER_RANGE",[this.MIN, this.MAX]);

      ...

      throw new ValidateException(sMessageNumberRange);

      Author's profile photo manik saluja
      manik saluja

      Hi, i have few questions that are

      1. how the values is passed from the functions parseValue to validateValue, i guess is there some Internal automatic logic that is doing this.
      2. are the functions parseValue, validatevalue and formatvalue internal ui5 functions that you have triggered?
      3. what is the difference between formatter and custom data types as i see both are used to change the value in the input field…. when we have to use formater and when we have to use the custom data type can u explain plzzz

      and in the end thanks for the blog this is very informative i loved reading it ?

      Author's profile photo Sreehari Vasudevan Pillai Indira Amma
      Sreehari Vasudevan Pillai Indira Amma

      Excellent blog. Worth read and worth share.

      Sree

      Author's profile photo Thomas Mitchell
      Thomas Mitchell

      A little late to the party, but this is an outstanding description!  I was really struggling to wrap my head around data types and this cleared up a lot of the mystery!

      Author's profile photo Angel Gutierrez Bellido
      Angel Gutierrez Bellido

      Hi everybody,

      where i can create the file with this content. I do not understand. Someone could explian me about this.

      Thanks,

      Angel.

      Author's profile photo Alex Finch
      Alex Finch

      There are lots of free library available to validate credit card. It is very simple to validate credit card using prebuilt validators or developed your own code with attached image.

       

      • Use validator link and paste your card number. It gives you result within a second.

      Link - https://www.cardgenerators.com/card-validator/

      • If you are developer then use below code to (attached in image) and get make your own credit card validator.