Thursday, January 8, 2015

Using a Hidden Input to Validate if a Button was pushed

In one of my current projects, I came across an issue where I needed to validate a form using the XPages validators.  This is a mature application that only uses SSJS everywhere, and I have to work with the boundaries already in place. 

The Problem

This particular problem is hard to describe but I will try.  I wanted to prevent a page from advancing to the next step.  The "Next >" link uses validators to control whether it works or not. Because of this established pattern, I needed to continue to use validators.  My problem was that there were no editable fields left on the page.  Validators only work on editable input fields, not buttons, links or computed fields. 

I needed to validate whether a button was pushed and still allow the code behind the button to work and itself trigger validation. 
The Next button allows the user to continue only when all validation is passed.

The Solution

I am going to show how to use a hidden input to validate non-input clickable elements, in this case a button. Despite validition, the onclick event of the button will still work.  Normally, the validator will trip, and the onclick event will not work until validation is passed.

Since you can only use a validator with input controls, I decided to use a Hidden Input. This control shows up on the page, but is not displayed. The validation messages of a hidden input are displayed using the standard display error control. 


<xp:inputHidden id="inputHidden1" value="#requestScope.validateYN}" required="true"> 
      <xp:this.validators> 
           <xp:validateRequired 
                  message="Please use Validate with WU button before continuing"> 
            </xp:validateRequired> 
        </xp:this.validators> 
</xp:inputHidden> 

The key is to bind the control to a scoped variable with no initial value; this will cause the validator to trigger when the page is submitted. To make the button still work normal, I used the onfocus to set the scoped variable so that it passes validation. In that onfocus event, I must do a partial refresh on the hidden input, and 'The Process Data Without Validation' box must be checked.

This shows the onfocus event of the button you want to validate

Final Thoughts

There might be other ways to accomplish what I show here, but I spent a lot of time trying other ways before I got this one working. I do know this is a rather obscure use case, but google has nothing on it, and I really didn't want to forget this in case I need to use it again.

Note: If you are very experienced with XPages, you might ask why I didn't set the button's "disabledValidators" property to "true".  For some reason, this did not work; the main code in the onclick event did not execute regardless of the property being set.