Quantcast
Channel: SAPUI5 Developer Center
Viewing all articles
Browse latest Browse all 789

Generic UI5 form validator

$
0
0

A common usecase is to have a form -- or multiple forms -- which should be validated upon clicking a "Submit" button. The UI5 validation mechanism by default does a terrific good job for inline validation (i.e. validating fields right after you have changed them, giving immediate feedback to the user) but this can lead to some issues.

 

Imagine a form with a couple of input fields which require a value. However, since they are initially empty, leaving them blank does not trigger a change event (and subsequent validation), so you could possibly submit your form without entering any data.

 

Or imagine you have a page with multiple forms, with input fields which depend on each other, and you want to validate all forms and their fields at once when clicking the "Submit" button.

 

Those cases are examples where after submit validation is more appropriate, and I will show how this can be achieved by still using the standard UI5 validation mechanism.

 

I have created a simple class which will validate your form(s) upon submitting it, and the implementation is pretty simple. But first, let me explain a bit about the standard validation mechanism.

 

 

To enable standard, inline validation of a control, you should do at least the following:

  1. Attach to the core's validationError and validationSuccess error handlers
  2. Implement a contraint to the binding of your control

 

Attaching to the validation event handlers is pretty simple, and need only be done once (for instance in the view controller's onInit() event handler):

 

    onInit: function() {

        // Attaches validation handlers

        sap.ui.getCore().attachValidationError(function (oEvent) {

            oEvent.getParameter("element").setValueState(ValueState.Error);

        });

        sap.ui.getCore().attachValidationSuccess(function (oEvent) {

            oEvent.getParameter("element").setValueState(ValueState.None);

        });

    }

 

Setting a constraint to a control is done using the UI5 Simple Types. For instance, to set an input field to required, you can simply use this:

 

    <Label text="Name" required="true" />

    <Input value="{

        path : '/userName',

        type : 'sap.ui.model.type.String',

        constraints : {

            minLength : 2

        }

    }"/>

 

You could even use regular expressions, for instance for validating an email address:

 

    <Label text="Email" required="true" />

    <Input value="{

        path : '/userEmail',

        type : 'sap.ui.model.type.String',

        constraints : {

            search : '\\S+@\\S+\\.\\S+'

        }

    }"/>

 

(The above example uses rather basic email validation, just a simple 'lorem@ipsum.dolor'. Use a more robust regex productively!)

 

If you implement this in a UI5 page, and type a name of 1 character or supply an invalid email address, you will see the controls will be surrounded with a red border, and the validation error is displayed in a tooltip:

 

Screen Shot 2015-11-01 at 16.34.08.png

However, not entering anything will not trigger a validation...

 

I have created a simple class which takes care of the validation upon clicking a submit button, and the implementation is fairly simple:

 

    onSubmit: function() {

        // Create new validator instance

        var validator = new Validator();

 

        // Validate input fields against root page with id 'somePage'

        if (validator.validate(this.byId("somePage"))) {

            // perform the actual form submit here

        }

    }

 

You simply create a new instance of the class, and then call the only method of that class, 'validate'. The input parameter for that method is the ID of any page, control, or form you wish to set as the root container for your validation. The method returns 'true' if all fields are filled correctly (i.e., no constraints are violated), or false otherwise.

 

Below is a screenshot of the 'validate' method, and hopefully the inline comments explain everything that is happening:

 

Screen Shot 2015-11-01 at 16.59.28.png

In short:

 

  • Check if the supplied control is something that can be visible and actually is visible (no sense in checking anything that cannot be visible)
  • Then check if a constraint is set
  • If yes, then try validating the control as if it were an inline validation
  • However, if the control could not be validated, it may have aggregations that could be validated (i.e. it may be a form, a table, etc. which may hold child controls). We then check the children, and recursively call the validate method again

 

You can see a working demo of this 'after-submit validation' here.

 

The Validator code itself is available from GitHub. It is a simple, single file you may include in your project. If you find any bugs or room for improvement, please feel free to clone and submit any changes!

 

I hope some may find it useful!


Viewing all articles
Browse latest Browse all 789

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>