Showing posts with label Validation. Show all posts
Showing posts with label Validation. Show all posts

Thursday, March 17, 2016

Sort-of Validation Messages -- How to use Oracle JET Custom Messages

Let's say you have a required field on a form and a user doesn't enter anything into that field. That empty field deserves a validation error message. Oracle JET's built-in validation handles this scenario quite nicely. Let's consider another scenario: A user enters an invalid user name and password. Is this a validation issue or some other type of error? Could you write an Oracle JET validator for credentials validation? One of the key differences between the required validation and a credentials validation is the asynchronous data-driven nature of credentials validation. Validating credentials likely requires an Ajax request. What do you do while waiting for a response? Can you write a validator that waits for an Ajax response before returning true/false (Yes, but technically it would be a blocking SJax (synchronous) request and nobody likes blocking synchronous requests)? Does it even matter?

I am a fan of Oracle JET's inline messages. When writing the failure logic for a login page, my first question is, "How can I reuse those cool inline Oracle JET messages to tell the user that authentication failed?" I can't exactly write an authentication validator because of the asynchronous nature of credential validation. On form submit, I won't know if the credentials are valid until I receive a response. By that time, validation is over. An alternative is to notify the user through Oracle JET's inline messages. Keeping with the authentication example, let's say you have an ojInputPassword component and you want to display an error message under the password (inline) when authentication fails. To that ojInputPassword element, add a messagesCustom attribute and bind it to an observable. For example:

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

In your ViewModel you will have a corresponding observable definition for authenticationMessages like so:

self.authenticationMessages = ko.observableArray([]);

Then when that Ajax authentication request returns a failure, you can insert an object into that authenticationMessages observable like this:

self.authenticationMessages.push({
  summary: "Authentication failed",
  detail: "Invalid user ID or password",
  severity: oj.Message.SEVERITY_TYPE.ERROR
});

The invalidShown field of our oj.invalidComponentTracker (named tracker, see Validating Oracle JET Input Before Submission Take II) will now return true (tracker.invalidShown === true). Here is a sample showing the inline error message as well as the tracker object and authenticationMessages array.

So now our user knows that his or her credentials are invalid and can enter some new credentials. What about that visible error message? Since we didn't use a custom validator to display the message, it isn't going to disappear based on user input. Rather, we need to control the presence (or absence) of that error message. It is my thought that once the user changes the user ID or password, that error message should disappear and only reappear if the new credentials are invalid. I see two ways to make this happen:

  1. Bind an event handler to the change event of both the user ID and password fields
  2. Subscribe to the user ID and Password observables

Either is acceptable, but I prefer the subscription route. Here is what that might look like:

var resetAuthenticationFailure = function() {
  self.authenticationMessages.removeAll();
};

self.userid.subscribe(resetAuthenticationFailure);
self.password.subscribe(resetAuthenticationFailure);

In the code sample above (above the image), do you see the severity attribute of the new message object? The messagesCustom isn't just for error messages. Done right, you can use it for information and confirmation messages as well. To see a "kitchen sink" example of messagesCustom, visit the Help, Hints and Messaging: Inline Multiple Messages recipe of the Oracle JET Cookbook.

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.

Thursday, March 3, 2016

Validating Oracle JET Input Before Submission

Oracle JET includes a very convenient validation module to validate user input. Even though it validates input immediately, it only displays validation warnings/errors after a user visits a validated component. This is as it should be. Can you imagine visiting a data entry page that immediately displayed all validation errors before you entered your first value? Oracle JET quietly maintains a list of validation messages in the collection messagesHidden. You can see this in action by navigating over to the Validation recipe in the Oracle JET cookbook and then pasting the following into the console:

$("#username").ojInputText("option", "messagesHidden");

The result will look something like the following:

Now enter some data into the username field and replay the last console command (hint: use the up arrow). Notice that the result collection is now empty.

Now, let's say you have a data entry form and you want to ensure validation occurs before a user submits data. What if a user skipped over a required field? Now that the username field has a value, enter the following into the console:

$("#username").ojInputText("isValid");

The console should return true. Now you can confirm validation and cancel submission if the form fails validation, but what about displaying that validation error message for fields that fail validation? Refresh the recipe page so that username has no value and validation warnings are hidden and then type the following into the JavaScript console:

$("#username").ojInputText("validate");

That highly valuable validation error message should reappear.

That is great, but do I need to check the isValid status of every field in my form? Do I need to invoke the validate method on every input field? In a word: YES (Note: if you are using knockout, there is an easier way. See Validating Oracle JET Input Before Submission Take II). But don't worry, you don't have to list every single field. We can let jQuery selectors handle this for us. Here is how:


var validateSelector = function(selector, componentName) {
  // Note: using multi-step selectors for two reasons:
  // #1: make it easier to pass in distinct part of selector
  // #2: sizzle selectors work in reverse, so we want to narrow selected
  // elements BEFORE testing data-bind.
  $(selector)
    .filter("[data-bind]")
    .filter("[data-bind*='" + componentName + "']")
    .each(function() {
      //console.log("Invoking validator on", this);
      $(this)[componentName]("validate");
    });
};

var isValidSelector = function(selector, componentName) {

  var $elements = $(selector)
    .filter("[data-bind]") // has a data-bind attribute
    .filter("[data-bind*='" + componentName + "']");

  // using a for loop to exit immediately if false
  for (var idx = 0, len = $elements.length; idx < len; idx++) {
    if (!$($elements[idx])[componentName]("isValid")) {
      return false;
    }
  }

  // fell through, so return true
  return true;
};


validateSelector("input[type='text']", "ojInputText");
validateSelector("input[type='password']", "ojInputPassword");
validateSelector("select", "ojSelect");

// first selector to fail will end the chain and return false
var formIsValid = isValidSelector("input[type='text']", "ojInputText") &&
  isValidSelector("input[type='password']", "ojInputPassword") &&
  isValidSelector("select", "ojSelect");

I certainly haven't covered every selector possible, but hopefully this is enough to communicate the idea. Of course, you don't want to paste this code into every single ViewModel. Instead, throw it into a RequireJS module and include it in ViewModels that require validation. In fact, why not display messages and check the validation status all at once by writing the module to just expose a single method that does both?

... Or, if you are using knockout, you could skip the whole jQuery selector thing by using an oj.invalidComponentTracker (Thank you JB for showing me this feature).