Thursday, March 17, 2016

Validating Oracle JET Input Before Submission Take II

For a blogger, I would say the best part about blogging is learning something new from a reader. My latest schooling comes from Oracle JET expert JB and involves Oracle JET's built-in validation. I learned a lot about the jQuery syntax for validating unvisited form fields and confirming validation before submission while writing the post Validating Oracle JET Input Before Submission. This is great... if you are using jQuery. If you are using knockout, however, there is another way: oj.InvalidComponentTracker. Scroll down the oj.editableValue document until you see the Binding Attributes section. Every oj.editableValue (which includes ojInputText, ojInputPassword, ojSelect, and just about every other input type) has an invalidComponentTracker attribute. Just set each validated input field's invalidComponentTracker attribute to the same observable and then you can test that one observable from your submit function. The App Level Validation: Dynamic Form Example cookbook recipe is a great example. Here are the basics: in your ViewModel, add:

self.tracker = ko.observable();

For each validated input in the view, add the invalidComponentTracker attribute like this:

<input id="password" required data-bind="ojComponent: {
    component: 'ojInputPassword', value: user.password,
    invalidComponentTracker: tracker}" type="password">

Oracle JET will will set the tracker observable to an instance of oj.InvalidComponentTracker. In your submit handler you can test for invalidHidden and invalidShown messages. If either of those fields return true, then you know the form contains invalid input. For visited fields, validation failure messages should be visible. For unvisited fields, you can make validation messages visible by invoking the oj.InvalidComponentTracker showMessages method.

Here is an example of the JavaScript I now use in my form submit routine to ensure validation was successful prior to submission:

var tracker = self.tracker();
if (tracker.invalidHidden || tracker.invalidShown) {
  tracker.showMessages();
  tracker.focusOnFirstInvalid();
  return;
}

Tip: Be sure to add 'ojs/ojknockout-validation' to your ViewModel's define/require block.

No comments:

Post a Comment